我正在使用tidyterra绘制一张上面有ggplot2个点的栅格 map :

library(ggplot2)
library(rnaturalearth)
library(terra)
library(tidyterra)

backmap <- ne_download(scale=50, type="MSR_50M", category="raster") # will download a 17MB map
data <- data.frame(longitude=runif(10, -180, 180), latitude=runif(10, -90, 90)) # simulate points

ggplot(data, aes(longitude, latitude)) +
  geom_spatraster(data=backmap) +
  geom_point() +
  coord_sf(crs='+proj=lonlat', expand=F)

Plot1

I would like to have the graticules drawn above the raster map,目前它们位于其下方,并且仅在贴图不完全不透明时可见:

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

Plot2_alpha

我知道我可以像在this SO answer中描述的那样使用theme(panel.background=element_blank(), panel.ontop=T)来使网格高于一切,但是点在网格之下是我不喜欢的.

我知道有一个变通办法,在this SO answer个中建议sf::st_graticule()个,但我想知道ggplot2个魔术师能否解决绘制相同网格两次的冗余问题.

推荐答案

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

library(tibble)
library(tidyterra)
library(sf)
library(ggplot2)

# Sample point data
set.seed(1)
data <- tibble(longitude=runif(10, -180, 180),
               latitude=runif(10, -90, 90))

# Generate graticules
graticules <- st_graticule(lon = seq(-180,180, 60),
                           lat = seq(-90,90, 30)) %>%
  vect()

ggplot() +
  geom_spatraster(data = backmap) + 
  geom_sf(data = graticules, color = "red") +
  geom_point(data = data,
          aes(x = longitude, y = latitude),
          color = "black") +
  coord_sf(expand = FALSE) +
  scale_x_continuous(breaks = seq(-180, 180, by = 60)) +
  scale_y_continuous(breaks = seq(-90, 90, by = 30)) +
  theme(legend.position = "none")

result

R相关问答推荐

geom_raster不适用于x比例中超过2,15的值

按块将载体转换为矩阵-reshape

ggplot 2中的地块底图(basemaps_gglayer()不起作用)

在(g)子中使用asserable字符

过滤器数据.基于两列的帧行和R中的外部向量

有没有一个R函数允许你从一个数字变量中提取一个数字,而不考虑它的位置(不仅仅是第一个或最后一个数字?

在特定Quarto(reveal.js)幻灯片上隐藏徽标

使用ggsankey调整Sankey图中单个 node 上的标签

当我们有多个特殊字符时,使用gsub删除名称和代码'

将重复项转换为NA

根据1个变量绘制 colored颜色 发散的 map ,由另一个变量绘制饱和度,ggplot2不工作

如何在R中平滑地绘制线图(不拟合)?

根据另一列中的值和条件查找新列的值

在数据帧列表上绘制GGPUP

我将工作代码重构为一个函数--现在我想不出如何传递轴列参数

通过初始的shiny 应用更新部署的shiny 应用的数据和参数,其中部署的应用程序显示为URL

自定义交互作用图的标签

在REST API中使用参数R

R:水平旋转图

使用dplyr删除具有条件的行