0

我正在尝试在 ggmap 图上绘制一个带有经度/纬度坐标的矩阵(主要是带有几个 NA 的随机数)。

这是我的代码:

library(ggmap)
library(ggplot2)

定义经度和纬度坐标

x1=34.2
x2=42.4
y1=37.4
y2=29.4
lon = seq(x1,x2,by=0.1)
lat = seq(y1,y2,by=-0.1)

定义具有经度/纬度维度的随机数矩阵

set.seed(1)
numbers = rnorm(length(lon)*length(lat))
var = matrix(numbers,length(lon),length(lat))

向矩阵添加一些 NA

var[1:5,1:5] = NA

lat_min <- min(lat)-0.3
lon_min <- min(lon)-0.3
lat_max <- max(lat)+0.3
lon_max <- max(lon)+0.3

构建ggmap

map_box <- c(left=lon_min,bottom=lat_min,
            right=lon_max,top=lat_max)
total_stmap <- get_stamenmap(bbox=map_box,zoom=5,maptype="toner")
total_ggmap <- ggmap(total_stmap,extent="panel")

制作一个 data.frame 将每个矩阵索引归因于地理坐标

lat_df <- c()
lon_df <- c()
var_df <- c()
for (i in 1:length(lon)) {
  for (j in 1:length(lat)) {
    lon_df <- c(lon_df,lon[i])
    lat_df <- c(lat_df,lat[j])
    var_df = var[i,j]
  }
}
df=data.frame(Longitude=lon_df,Latitude=lat_df,Variable=var_df)

使用 ggmap 和 geom_tile 进行绘图

plot = total_ggmap +
geom_tile(data=df,aes(x=Longitude,y=Latitude,fill=Variable),alpha=1/2,color="black",size=0) +
geom_sf(data = df, inherit.aes = FALSE, fill = NA)

使用此代码,我收到消息:

Coordinate system already present. Adding new coordinate system, which will replace the existing one.

...和一个空白的情节。

4

1 回答 1

2

这里有两个问题。首先是Variable列中的所有值都是相同的,因为您只是var_df在循环的每次迭代中覆盖。线

var_df = var[i,j]

应该

var_df = c(var_df, var[i,j])

geom_sf其次,如果您有经度、纬度和值的数据框,则不应使用。geom_sf用于绘制sf对象,这不是您所拥有的。

相反,您只需要做:

plot <- total_ggmap +
   geom_tile(data = df, aes(Longitude, Latitude, fill = Variable), alpha = 1/2, size = 0)

你得到:

plot

在此处输入图像描述

于 2022-02-22T20:01:30.060 回答