【问题标题】:Crop geographical boundaries in a heatmap in r ggplot在 r ggplot 的热图中裁剪地理边界
【发布时间】:2021-02-15 10:22:46
【问题描述】:

我正在尝试在地理边界内裁剪热图(或“geom_tile”)。

我为沿经度和纬度坐标的热图定义了一个随机数据框。

set.seed(20)
lon = seq(from = 3.4, to = 6.3, by = 0.1)
lat = seq(from = 13.3, to = 10.1, by = -0.1)

lati <- c()
long <- c()
for (i in 1:length(lat)) {
  for (j in 1:length(lon)) {
    lati <- c(lati,lat[i])
    long <- c(long,lon[j])
  }
}

vals = rnorm(length(lati))

df <- data.frame(
longitude=long,
latitude=lati,
value=vals)

然后我划定地理边界,专门针对尼日利亚的 Kebbi 州。

library(raster)
library(sf)
nga <- getData('GADM', country='NGA', level=1)
keb <- subset(nga,NAME_1 %in% "Kebbi")
keb2 <- st_as_sf(keb)

然后我结合热图和地理边界:

library(ggplot2)
tilekeb <- ggplot() + geom_tile(data=df,aes(x=longitude,y=latitude,fill=vals),alpha=1/2,color="black",size=0) +
  geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)

这会产生:

我的目标是剪切(裁剪)边界之外的部分,仅将热图留在有限的地理边界内。有人对如何在 R/ggplot 中做到这一点有想法吗?

谢谢

【问题讨论】:

标签: r ggplot2 geospatial crop


【解决方案1】:

我实际上使用raster 来完成这项工作

# create spatial points data frame from your df
spg <- df
coordinates(spg) <- ~ longitude + latitude
# coerce to SpatialPixelsDataFrame
gridded(spg) <- TRUE
# coerce to raster
rasterDF <- raster(spg)
# then I crop
plot(rasterDF)
rasterDF_crop <- crop(rasterDF, extent(keb2))
plot(rasterDF_crop)
rasterDF_masked <- mask(rasterDF_crop, keb2)
plot(rasterDF_masked)

然后我将其转换回数据框:

df_masked <- raster::as.data.frame(rasterDF_masked,xy=TRUE)
colnames(df_masked) <- colnames(df)

并使用您的代码再次绘制它

library(ggplot2)
tilekeb <- ggplot() + geom_tile(data=df_masked,aes(x=longitude,y=latitude,fill=value),alpha=1/2,color="black",size=0) +
  geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)

tilekeb

【讨论】:

  • 非常感谢,这正是我想要的!
猜你喜欢
  • 2022-06-23
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
相关资源
最近更新 更多