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

时间:2018-04-14 21:02:41

标签: r ggplot2 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()
  )

返回

scatterplot no grid

但是在使用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()
  )

enter image description here

2 个答案:

答案 0 :(得分:16)

此问题在ggplot2 github site上提出。您可以通过将网格线的颜色设置为透明,panel.grid.major=element_line(colour="transparent")或在调用coord_sf(datum=NA)后添加geom_sf 来删除网格线。

答案 1 :(得分:0)

另一种移除网格线的方法是使用 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)) 会产生错误。

enter image description here