In a choropleth graphic map with ggplot2, an element corresponding to the NA values of the variable Cuantil Esfuerzo Social por habitante
is automatically included in the legend
I have tried a few things:
- Using
na.translate = F
inscale_fill_manual()
hides both the "NA" item from the legend and the polygons corresponding to those values. So the map is incomplete. - Another option that I have used (as it appears in the code) is to define a color and a specific label (Sin datos) for the "NA" values to give more meaning to the graph.
There would be two options to build the graph according to the needs:
- Hide in the legend the label of the "NA" values. And add an annotation (
annotate()
) for the "NA" values, with a rectangle and text. - To be able to separate (adding a space) the legend with the quartile intervals and a different one only with the corresponding,
key
andlabel
, to the "NA" values.
Data: https://www.dropbox.com/s/b39pp4qmbhns658/geosmunicipiosmu.R?dl=0
Code:
library(ggplot2)
geosmunicipiosmu <- dget("geosmunicipiosmu.R")
colors = c("#fee5d9","#fcae91","#fb6a4a","#de2d26")
mapaemu <- ggplot(geosmunicipiosmu) +
geom_sf(
aes(
fill = `Cuantil Esfuerzo Social por habitante`
),
#fill="white",
#fill=NA,
color="#FFFFFF",
size=0.5
) +
coord_sf(
xlim = c(-3.1, -0.5)
) +
theme_void() +
scale_fill_manual(
values = c(colors,"#2c2c2c"), # Color adicional para los valores "NA"
labels = c(
paste("[1Q]\n", format(cuartilin[2], big.mark=".", decimal.mark=",", nsmall = 2, digits = 2), "€", sep=""),
paste("(2Q]\n", format(cuartilin[3], big.mark=".", decimal.mark=",", nsmall = 2, digits = 2), "€", sep=""),
paste("(3Q]\n", format(cuartilin[4], big.mark=".", decimal.mark=",", nsmall = 2, digits = 2), "€", sep=""),
paste("(4Q]\n", format(cuartilin[5], big.mark=".", decimal.mark=",", nsmall = 2, digits = 2), "€", sep=""),
"Sin\ndatos" # Etiqueta personalizada para valores "NA"
),
guide = guide_legend(
direction = "horizontal",
nrow = 1,
label.position = "top",
label.hjust = 1,
keyheight = 0.75
)
) +
labs(
title = "Título",
subtitle = "Subtítulo",
fill = "" # Etiqueta para la Leyenda
) +
theme(
text = element_text(color = "#22211d"),
plot.background = element_rect(fill = "#ffffff", color = NA),
panel.background = element_rect(fill = "#ffffff", color = NA),
legend.background = element_rect(fill = "#ffffff", color = NA),
plot.caption.position = "plot",
legend.position = "bottom",
legend.text = element_text(size = 14)
)
mapaemu
The map right now: