【问题标题】:Can't remove gridlines when plotting with geom_sf使用 geom_sf 绘图时无法删除网格线
【发布时间】:2018-09-24 22:42:26
【问题描述】:

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

返回

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

【问题讨论】:

    标签: r ggplot2 sf


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      1. 使用theme(panel.grid.major = element_line(colour = "transparent"))将网格线的颜色设置为透明

      2. 添加coord_sf(datum = NA)调用geom_sf

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        相关资源
        最近更新 更多