在`ggplot2`中显示位于`geom_spatraster`上方但数据点下方的网格线?

9avjhtql  于 2024-01-03  发布在  其他
关注(0)|答案(2)|浏览(132)

我正在使用tidyterraggplot2中绘制一个带有点的光栅Map:

  1. library(ggplot2)
  2. library(rnaturalearth)
  3. library(terra)
  4. library(tidyterra)
  5. backmap <- ne_download(scale=50, type="MSR_50M", category="raster") # will download a 17MB map
  6. data <- data.frame(longitude=runif(10, -180, 180), latitude=runif(10, -90, 90)) # simulate points
  7. ggplot(data, aes(longitude, latitude)) +
  8. geom_spatraster(data=backmap) +
  9. geom_point() +
  10. coord_sf(crs='+proj=lonlat', expand=F)

字符串


的数据

我想在光栅Map上方绘制经纬网,因为现在它们在光栅Map下方,只有在Map不是完全不透明的情况下才可见:

  1. ggplot(data, aes(longitude, latitude)) +
  2. geom_spatraster(data=backmap, alpha=.5) +
  3. geom_point() +
  4. coord_sf(crs='+proj=lonlat', expand=F)



我知道我可以像this SO answer中描述的那样使用theme(panel.background=element_blank(), panel.ontop=T)将网格置于所有内容之上,但是这样的话,我不喜欢网格之下的点。
我知道在this SO answer中建议的sf::st_graticule()的解决方案,但想知道是否可以通过ggplot2魔术师解决两次绘制相同网格的冗余。

aiazj4mn

aiazj4mn1#

sf包是你的好朋友。请注意示例图像中巴布亚新几内亚上方的点,它位于网格的前面。此外,最好将所有空间矢量数据(如点)转换为具有定义crs的sf对象。我省略了光栅导入步骤,但保持对象名称不变:

  1. library(tibble)
  2. library(tidyterra)
  3. library(sf)
  4. library(ggplot2)
  5. # Sample point data
  6. set.seed(1)
  7. data <- tibble(longitude=runif(10, -180, 180),
  8. latitude=runif(10, -90, 90))
  9. # Generate graticules
  10. graticules <- st_graticule(lon = seq(-180,180, 60),
  11. lat = seq(-90,90, 30)) %>%
  12. vect()
  13. ggplot() +
  14. geom_spatraster(data = backmap) +
  15. geom_sf(data = graticules, color = "red") +
  16. geom_point(data = data,
  17. aes(x = longitude, y = latitude),
  18. color = "black") +
  19. coord_sf(expand = FALSE) +
  20. scale_x_continuous(breaks = seq(-180, 180, by = 60)) +
  21. scale_y_continuous(breaks = seq(-90, 90, by = 30)) +
  22. theme(legend.position = "none")

字符串


的数据

展开查看全部
wribegjk

wribegjk2#

我在安装(tidy)terra时遇到了麻烦,所以我不知道这是否适用于您的数据对象,但通常情况下,您可以在栅格和点之间添加手动经纬网。

  1. library(ggplot2)
  2. library(maps)
  3. world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))
  4. ggplot(world1) +
  5. geom_sf() +
  6. geom_sf(data = sf::st_graticule(world1), colour = "red")
  7. # geom_point()

字符串
x1c 0d1x的数据
创建于2023-12-13使用reprex v2.0.2

相关问题