Search code examples
rggplot2plotcolorsfill

ggplot: is it possible to overlap 2 plots?


I'm drawing two maps of my country using shapefiles: one for regions with real wage lower than 700 and the other one for the regions with real wage greater than 700. This is my code

plot 1 <-right_join(prov2022, dataset, by = "COD_PROV") %>% 
         ggplot(aes(fill = `Real Wage` < 700))+
         geom_sf() +
         theme_void() +
         theme(legend.position = "none", legend.title=element_blank())+
         scale_fill_manual(values = c('white', 'orange'))
  

plot 2<- right_join(prov2022, dataset, by = "COD_PROV") %>% 
         ggplot(aes(fill = `Real Wage` > 700))+
         geom_sf() +
         theme_void() +
         theme(legend.position = "none", legend.title=element_blank())+
         scale_fill_manual(values = c('white', 'red'))

It works perfectly.

Is there a way to overlap the second plot on the first one?? More precisely, I need to put the filled regions of the second plot into the first one


Solution

  • You could create one map and use e.g. dplyr::case_when to create intervals to be mapped on fill or use cut.

    Using the default example from ggplot2::geom_sf:

    library(ggplot2)
    library(sf)
    #> Linking to GEOS 3.10.2, GDAL 3.4.2, PROJ 8.2.1; sf_use_s2() is TRUE
    
    nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
    
    ggplot(nc) +
      geom_sf(aes(fill = dplyr::case_when(
        AREA < .1 ~ "a",
        AREA > .15 ~ "c",
        .default = "b"
      ))) +
      scale_fill_manual(
        values = c("red", "white", "orange"),
        labels = c(a = "< .1", b = ".1 <= x <= .15", c = "> .15")
      ) +
      labs(fill = NULL)
    

    EDIT To add more colors or categories add more conditions to case_when. However, if you have a lot of conditions then using cut might be the easier approach.

    Note: In case you wondered about why I use the letters. This was a quick and easy approach to order the categories.

    library(ggplot2)
    library(sf)
    #> Linking to GEOS 3.10.2, GDAL 3.4.2, PROJ 8.2.1; sf_use_s2() is TRUE
    
    nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
    
    ggplot(nc) +
      geom_sf(aes(fill = dplyr::case_when(
        AREA < .05 ~ "a",
        AREA >= .05 & AREA < .1 ~ "b",
        AREA > .15 & AREA < .2 ~ "c",
        .default = "d"
      ))) +
      scale_fill_manual(
        values = c("red", "orange", "brown", "white"),
        labels = c(a = "< .05", b = ".05 <= x < .1", c = "> .15" , d = ".1 <= x <= .15 OR x > .2")
      ) +
      labs(fill = NULL)