2

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.

Rik Ferreira
  • 161
  • 1
  • 10
  • More than only semantics, and to clarify the grammar of graphics (the gg bit in ggplot) - legends will always map to an aesthetic, i.e., to the "look" of your geom. – tjebo Dec 04 '21 at 10:17
  • Does this answer your question? [Legends for multiple fills in ggplot](https://stackoverflow.com/questions/39185291/legends-for-multiple-fills-in-ggplot) – tjebo Dec 04 '21 at 10:18
  • No, but stefan's answer solves the problem. Thank you! – Rik Ferreira Dec 04 '21 at 14:07

1 Answers1

2

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)

stefan
  • 90,330
  • 6
  • 25
  • 51