Home > Software engineering >  Legend based on geom rather than aesthetic with ggplot
Legend based on geom rather than aesthetic with ggplot

Time:12-04

The idea here is to draw a legend for each geom with the same aesthetic. In the example below the legend generated assumes that these two different layers are in the same scale, resulting in this map.

I want, as a result, that the legend in the graph is separated in two, so I can change these with a scale_fill_* for each layer.

I'm aware of this solution: enter image description here

Thanks.

CodePudding user response:

Sounds as if you are looking for the ggnewscale package which allows for multiple scales and guides for the same aesthetic:

library(tidyverse)
library(sf)
library(geobr)
library(ggnewscale)

pal1 <- scales::hue_pal()(8)[1:4]
pal2 <- scales::hue_pal()(8)[5:8]

ggplot()  
  geom_sf(data = mun[[1]], aes(fill = index))  
  scale_fill_manual(values = pal1)  
  new_scale_fill()  
  geom_sf(data = mun[[2]], aes(fill = index))  
  scale_fill_manual(values = pal2)

  • Related