How do I add the legend of each layer to my ggplot map?

Viewed 178

I am creating a map with different provinces and have 4 point layers over this map each from their own source. When I add the layers to create the map, I only get a legend for the provinces of the map, not for the rest of the layers.

Province %>% group_by(ProvinceNa) %>% 
  summarize() %>% 
  ggplot() + 
    geom_sf(aes(fill = ProvinceNa)) + 
    scale_fill_grey() +
    geom_sf(data = It, col = "yellow") + 
    geom_sf(data = Io, col = "blue") +
    geom_sf(data = Ib, col = "brown") +
    geom_sf(data = Ie, col = "green")
2 Answers

If you want to have a legend map on aesthetics, i.e. use e.g. geom_sf(data = It, aes(color = "yellow")). To get the right colors add scale_color_identity(guide = "legend").

EDIT To change the labels you could pass a named vector to the labels argument of scale_color_identity to assign color names to labels.

Making use of the default example data from ?ggplot2::geom_sf:

library(ggplot2)
library(sf)
#> Linking to GEOS 3.8.1, GDAL 3.2.1, PROJ 7.2.1

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

ggplot() +
  geom_sf(data = nc, aes(fill = AREA)) +
  geom_sf(data = nc, aes(colour = "yellow"), fill = NA) +
  scale_color_identity(labels = c(yellow = "Yellow Label"), guide = "legend")

map

This is my coding:

Province %>% group_by(ProvinceNa) %>% 
summarize() %>% 
ggplot() + 
geom_sf(aes(fill = ProvinceNa)) + scale_fill_grey("Provinces") +
geom_sf(data=It, aes(col = "yellow")) + 
geom_sf(data=Io, aes(col = "blue")) +
geom_sf(data=Ib, aes(col = "Brown")) +
geom_sf(data=Ie, aes(col="green")) +
scale_color_identity(name = "Species", labels = c(yellow = "Ichnochiton textilis", blue = "Ichnochiton oniscus", Brown = "Ischnochiton bergoti", green = "Ischnochiton elizabethensis"),guide = "legend")
Related