在下面的代码中,我尝试使用ggmap().
将kriged meuse数据叠加到谷歌地图上代码似乎一直运行到get_map(),
但是陷入了某种巨大的困境在最后print(ggmap())
执行时,计算(我的8G机器上的RAM使用量跳到7G - 被警告!)。我做错了什么?
更新:我想我发现了问题=> stat_contour()
似乎无法使用kriged数据(仍然不确定原因)。当我用分箱函数stat_summary_2d(),
替换它时,代码现在可以正常工作。如果可能的话,我还是想展示轮廓线。有人可以帮忙吗?
由于
# transform meuse data to SpatialPointsDataFrame
suppressMessages(library(sp))
data(meuse)
coordinates(meuse) <- ~ x + y
proj4string(meuse) <- CRS("+proj=stere
+lat_0=52.15616055555555 +lon_0=5.38763888888889
+k=0.999908 +x_0=155000 +y_0=463000
+ellps=bessel +units=m +no_defs
+towgs84=565.2369,50.0087,465.658,
-0.406857330322398,0.350732676542563,-1.8703473836068, 4.0812")
# define sample grid for kriging
set.seed(42)
grid <-spsample(meuse, type = "regular", n = 10000)
# do kriging
suppressMessages(library(automap))
krg <- autoKrige(formula = copper ~ 1,
input_data = meuse,
new_data = grid)
# extract kriged data
krg_df <- data.frame(krg$krige_output@coords,
pred = krg$krige_output@data$var1.pred)
names(krg_df) <- c("x", "y", "pred")
# transform to SpatialPointsDF & assign original (meuse) projection
krg_spdf <- krg_df
coordinates(krg_spdf) <- ~ x + y
proj4string(krg_spdf) <- proj4string(meuse)
# transform again to longlat coordinates (for overlaying on google map below)
krg_spdf <- spTransform(krg_spdf, CRS("+init=epsg:4326"))
krg_df <- data.frame(krg_spdf@coords, pred = krg_spdf@data$pred)
# get meuse map and overlay kriged data
suppressMessages(library(ggmap))
lon <- range(krg_df$x)
lat <- range(krg_df$y)
meuse_map <- get_map(location = c(lon = mean(lon), lat = mean(lat)),
zoom = 13)
print(ggmap(meuse_map, extent = "normal", maprange = F) +
#### old code (does not work) ####
#stat_contour(aes(x = x, y = y, z = pred, fill = ..level..),
# alpha = 0.5,
# color = "gray80",
# geom = "polygon",
# data = df) +
#### replaced with stat_summary_2d() ####
stat_summary_2d(aes(x = x, y = y, z = pred),
binwidth = c(0.0005,0.0005),
alpha = 0.5,
data = krg_df) +
scale_fill_gradient(low = "yellow",
high = "red",
name = "Copper") +
coord_cartesian(xlim = lon, ylim = lat, expand = 0) +
theme(aspect.ratio = 1))