使用 geom_sf 绘图时无法删除网格线

Can't remove gridlines when plotting with geom_sf

在使用 geom_sf 绘图时,删除网格线的标准方法似乎是徒劳的。

例如,如果我们绘制一个简单的 ggplot 对象,这可以移除网格

library(tidyverse)
library(sf)

mtcars %>%
  ggplot(
    aes(disp, hp)
  ) +
  geom_point() +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank()
  )

returns

但是当您使用 geom_sf

绘图时,相同的代码无法删除网格
"shape/nc.shp" %>% 
  system.file(
    package = "sf"
  ) %>% 
  st_read(
    quiet = TRUE
    ) %>%
  ggplot() +
  geom_sf(aes(fill = AREA)) +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank()
  )

此问题已在 ggplot2 github site 上提出。您可以通过以下任一方式删除网格线:

  1. 使用theme(panel.grid.major = element_line(colour = "transparent"))

  2. 将网格线的颜色设置为透明
  3. 在调用geom_sf

  4. 后添加coord_sf(datum = NA)

另一种删除网格线的方法是使用 scale_x_continuous:

更改比例
library(ggplot2)
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")

crs_robinson = "+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m no_defs"

ggplot() + 
  geom_sf(data = world, color="grey70", fill="grey70")  +
  theme(panel.border=element_blank(),
        panel.grid = element_line(colour = "grey70", size=2),
        axis.text.x= element_blank(),
        axis.text.y = element_blank()) + 
  labs(title = str_c("Map of without gridlines") ,
       x = "",
       y = "") +
  scale_x_continuous(breaks = c(-180, 180)) +
  scale_y_continuous(breaks=c(-89.999, 89.999)) +
  coord_sf(crs = "+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m no_defs", expand = TRUE)no_defs", expand = TRUE)

PS:注意x scale_y_continuous(breaks=c(-90, 90))会报错。