Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove gridlines when plotting with geom_sf

Tags:

r

ggplot2

sf

The standard means of removing gridlines seem futile when plotting with geom_sf.

For instance, if we plot a simple ggplot object, this works to remove the grid

library(tidyverse)
library(sf)

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

returns

scatterplot no grid

but the same code fails to remove the grid when you plot using 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

like image 840
tomw Avatar asked Apr 14 '18 21:04

tomw


2 Answers

This issue was raised on the ggplot2 github site. You can remove the gridlines by either of:

  1. Setting the colour of the gridlines to be transparent with theme(panel.grid.major = element_line(colour = "transparent"))

  2. Adding coord_sf(datum = NA) after calling geom_sf

like image 78
eipi10 Avatar answered Oct 13 '22 02:10

eipi10


Another way to remove the gridlines is to change the scale using 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: Note that that for x scale_y_continuous(breaks=c(-90, 90)) gives an error.

enter image description here

like image 1
Daniel Avatar answered Oct 13 '22 02:10

Daniel