Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I highlight some specific municipalities in a map with ggplot?

I am plotting the map of Málaga, Spain but I need to highlight in red (or any other color) some specific municipalities (those from the coast), coded in the file as "cmun" (005, 025, etc...). However, I am not able to select and plot them, leaving the remaining municipalities in gray. I tried to change the aes() adding a vector with the cmun codes c("005", "025", "041",...) but does not work and I get the error Error: Aesthetics must be either length 1 or the same as the data (2): fill. The cmun variable is a character one and I tried to transform in numeric but it does not work either.

I provide the code where the plot for Málaga works but I am stuck when I try put some municipalities in different color:

library(mapSpain)
library(ggplot2)

country <- esp_get_country()
lines <- esp_get_can_box()

# Plot municipalities

andalucia <- esp_get_ccaa("01")

malaga <- esp_get_munic(region = "Malaga")

malaga$name_eu <- esp_dict_translate(malaga$ine.prov.name, lang = "eu")

ggplot(malaga) +
   geom_sf(fill = "grey50") +
   geom_sf(data = malaga, aes(fill = name_eu)) +
   scale_fill_manual(values = "red2") +
   labs(
       fill = "",
       title = "Municipalities",
       subtitle = "Málaga"
       ) +
   theme_void() +
   theme(
   plot.title = element_text(face = "bold"),
   plot.subtitle = element_text(face = "italic")
)

I'd really appreciate any tips you can give me, I've been at it for days and I can't solve it. I assume my problem is how to isolate those municipalities to highlight but I don't know if I have to create them before the ggplot code or it can be done within. Thank you very much in advance.

like image 383
José Avatar asked Dec 06 '25 07:12

José


1 Answers

You are almost there. As with a normal ggplot graph, you need to have a column that can be used as a facet to fill in the colours. If you have a list of coastal municipalities you can use those to create a column like I do below with coastal_cmun. Use this column for the fill value and use scale_fill_manual (or any other discrete fill scale) to adjust the colours. Hide the legends if needed.

# coastal municipalities
coast <- c("005", "025", "041")
malaga$coastal_cmun <- ifelse(malaga$cmun %in% coast, "coast", "inland")


ggplot(malaga) +
  geom_sf(aes(fill = coastal_cmun)) +
  scale_fill_manual(values = c("red2", "grey50")) + # order by factor of coastal_cmun
  labs(
    fill = "",
    title = "Municipalities",
    subtitle = "Málaga"
  ) +
  theme_void() +
  theme(
    plot.title = element_text(face = "bold"),
    plot.subtitle = element_text(face = "italic")
  )

enter image description here

like image 196
phiver Avatar answered Dec 08 '25 20:12

phiver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!