Legend based on geom rather than aesthetic with ggplot

Viewed 61

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: https://stackoverflow.com/a/24874007/11056037, but I'm looking for a more elegant and scalable way to do this.

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

mun <- map(11:12, read_municipality) %>%
    map(mutate, index = seq_along(code_muni), .before = geom)

mun[[2]] <- mun[[2]] %>%
    mutate(index = index + 100)

mun <- mun %>%
    map(
        ~mutate(.x, index = cut(index, quantile(index), include.lowest = TRUE))
    )

ggplot() +
    geom_sf(data = mun[[1]], aes(fill = index)) +
    geom_sf(data = mun[[2]], aes(fill = index))

enter image description here

Thanks.

1 Answers

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