C. Braun
C. Braun

Reputation: 5201

Move ggplot2 gridlines to top layer but keep panel background

Using the sf package with ggplot2, gridlines are used to draw graticules. By setting panel.ontop to TRUE, it is possible to have the graticules on top of the map:

library(sf)
library(ggplot2)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

ggplot() +
    geom_sf(data = nc, fill='white') +
    coord_sf(expand = T) +
    theme(panel.border = element_rect(color = 'black', fill = NA),
          panel.background = element_blank(),
          panel.ontop = T,
          plot.background = element_rect(fill = "#ddefff"),
          axis.ticks = element_blank(),
          axis.text = element_blank()) +
    ggtitle("NC")

enter image description here

What I would like, however, is to be able to set the background color of the plot area, which would usually be done with panel.background. This obviously won't work here, as it would cover the map.

Desired result:

enter image description here

My initial thoughts are that I could first add a geom_rect the exact size of the panel area, but I am not sure how I would get those dimensions. How can I keep the gridlines on top, but still have a unique panel background color?

Edit

Adding on to the good answer from @sebdalgarno below, I found we can address the expansion problem using expand_range (as ggplot2 does internally):

bb <- st_bbox(nc)
bb[c(1,3,2,4)] <- c(scales::expand_range(c(bb$xmin, bb$xmax), mul = 0.05),
                    scales::expand_range(c(bb$ymin, bb$ymax), mul = 0.05))
bb <- bb %>% st_as_sfc() %>% st_sf()

This now gives the same expansion factor as if coord_sf(expand = T) were set.

Upvotes: 4

Views: 1765

Answers (1)

sebdalgarno
sebdalgarno

Reputation: 3197

This solution works with expand = F:

Following on your geom_rect suggestion turn the bbox into a sf polygon

bb <- st_bbox(nc) %>% st_as_sfc() %>% st_sf()

and plot with geom_sf

ggplot() +
  geom_sf(data = bb, fill = 'grey') +
  geom_sf(data = nc, fill='white') +
  coord_sf(expand = F) +
  theme(panel.border = element_rect(color = 'black', fill = NA),
        panel.background = element_blank(),
        panel.ontop = T,
        plot.background = element_rect(fill = "#ddefff"),
        axis.ticks = element_blank(),
        axis.text = element_blank()) +
  ggtitle("NC")

If you can figure out how to manually expand the bbox polygon by the same amount, this could work with expand = T

enter image description here

Upvotes: 3

Related Questions