Adding a legend to a ggplot map
Perhaps an inset bar chart instead:
library(ggplot2)
library(sf)
library(dplyr)
library(patchwork)
# Import a geojson or shapefile
map_ <- read_sf("https://raw.githubusercontent.com/R-CoderDotCom/data/main/shapefile_spain/spain.geojson") %>% 
  mutate(name = forcats::fct_reorder(name, desc(unemp_rate)))

g1 <- map_ %>% 
  ggplot() +
  geom_sf(color = "white", aes(fill = unemp_rate)) +
  geom_sf_text(aes(label = name), size = 2) +
  scale_fill_gradient2(low = "brown", high = "green", midpoint = 16) +
  theme_minimal() +
  theme(legend.position = "none", axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank())

g2 <- map_ %>% 
  ggplot(aes(x = unemp_rate, y = name, fill = unemp_rate)) +
  geom_col() + 
  scale_fill_gradient2(low = "brown", high = "green", midpoint = 16) +
  geom_text(aes(label = name, x = .5, hjust = 0)) +
  geom_text(aes(label = unemp_rate), nudge_x = - .5, hjust = 1) +
  theme_void() +
  theme(legend.position = "none")

g1 + inset_element(g2, 0, .2, .9, 1)



I am using ggplot2 to visualise map-related data. I have coloured regions according to a continuous value, and I would like to add a legend with colors and region names. My own data is a bit cumbersome to share, but I have recreated the scenario with public data (Mapping in ggplot2). The following code creates the included map:
library(ggplot2)
library(sf)

# Import a geojson or shapefile
map <- read_sf("https://raw.githubusercontent.com/R-CoderDotCom/data/main/shapefile_spain/spain.geojson")

ggplot(map) +
  geom_sf(color = "white", aes(fill = unemp_rate)) +
  geom_sf_text(aes(label = name), size = 2)


Instead of the continuous default legend, I would like to have a legend with names, numbers and colors. Basically, a legend that shows the name and unemp_rate columns of the data with colors matching the map (eg. unemp_rate). Somewhat like the legend of the second included picture (but the colors are not right).




name
unemp_rate




"Andalucía"
18.68


"Aragón"
8.96


"Principado de Asturias"
11.36


"Islas Baleares"
9.29


"Islas Canarias"
17.76


"Cantabria"
8.17


"Castilla y León"
10.19


"Castilla-La Mancha"
14.11


"Cataluña"
9.29


"Comunidad Valenciana"
12.81


"Extremadura"
16.73


"Galicia"
11.20


"Comunidad de Madrid"
10.18


"Región de Murcia"
12.18


"Comunidad Foral de Navarra"
8.76


"País Vasco"
8.75


"La Rioja"
10.19


"Ceuta y Melilla"
23.71





My actual code looks like so:
ggplot(map, aes(geometry = geometry, fill = Y1)) +
  theme_bw() + geom_sf(show.legend = FALSE) +
  scale_fill_gradient2(low = "brown", high = "green") +
  theme(
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank())

