我正在嘗試在 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.
...和一個空白的情節。
uj5u.com熱心網友回復:
這里有兩個問題。首先是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

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432009.html
