0

Following from this question on boxplots and my own question on making a map of India, what is a good way to avoid code repetition in ggplot when dealing with various layers of a map?

Below is a reprex . I thought the easiest way would be to: 1. save a basic map with state and national borders 2. add district layer (displaying the variables).

Imagine repeating step 2 for dozens of variables.

library(ggplot2)
library(sf)
library(raster)

# Download district and state data (should be less than 10 Mb in total)

distSF <- st_as_sf(getData("GADM",country="IND",level=2))

stateSF <- st_as_sf(getData("GADM",country="IND",level=1))

# Add country border

countryborder <- st_union(stateSF)

# STEP 1: Basic plot

basicIndia <- ggplot() +
  geom_sf(data = stateSF, color = "white", fill = NA) +
  geom_sf(data = countryborder, color = "blue", fill = NA) +
  theme_dark()

# STEP 2: Adding the data layer underneath so it doesn't cover the other borders

indiaMap$layers <- c(geom_sf(data = distSF, fill = "red")[[1]], indiaMap$layers[[2:3]])

indiaMap$layers <- c(geom_sf(data = distSF, fill = "gold")[[1]], indiaMap$layers[[2:3]])

indiaMap

However, in this way, one cannot make even minor modifications to that additional layer, like adding a different title. The following obviously does not work but makes my point.

basicIndia$layers <- c(
  geom_sf(data = distSF, aes(fill = GINI), color = "white", size = 0.2)[[1]] +
    labs(title = "Gini coefficient"), 
                       basicIndia$layers)

Am I approaching the problem in the wrong way? Is this something that cannot be done?

Fons MA
  • 1,142
  • 1
  • 12
  • 21

1 Answers1

1

Another way to approach the problem would be to use ggplot_build().

Make a ggplot_build object using:

indiaBuild <- ggplot_build(basicIndia)

Instead of your step 2 we could now use:

indiaBuild$plot$layers <- c(indiaBuild$plot$layers,
                            geom_sf(data=distSF, fill='gold')[[1]])

You can change various parts of the ggplot_build object then including the title:

indiaBuild$plot$labels$title <- 'Gini coefficient'

When finished you can extract just the plot using p <- indiaBuild$plot

Chris
  • 3,836
  • 1
  • 16
  • 34