I am trying to color a country map based on level of weather risk in each admin area. I believe this can best be done in R, though my knowledge of R is next to zero.
From this post cannot add labels for country with ggplot, geom_polygon and geom_text, I have been able to run the code and plot a risk map of all countries in Africa. I tried to adapt the code for my purpose as below:
library(sf)
library(ggplot2)
all_districts <- data.frame(region = c("Maseru",
"Butha-Buthe",
"Leribe",
"Berea",
"Mafeteng",
"Mohale's Hoek",
"Quthing",
"Qacha's Nek",
"Mokhotlong",
"Thaba-Tseka"),
risk = c(4, 4, 2, 1, 2, 4, 1, 3, 1, 2))
table(all_districts$risk)
mapdata_x <- map_data('world') %>% filter(region %in% all_districts$region)
mapdata_x <- mapdata_x %>% left_join(all_districts, by='region')
label_data <- mapdata_x %>% group_by(region) %>% filter(row_number() == 1)
ggplot(mapdata_x, aes (x = long, y = lat, group = group)) +
geom_polygon(aes(fill = factor(risk)), linewidth = 0.25, color = "black") +
scale_fill_manual(values = c("#a6d96a", "#ffffbf", "#fdae61", "#d7191c"),
name = "Risk Level") +
theme(axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.ticks = element_blank(),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
rect = element_blank())+
labs(title = "Weather Risk Levels") +
geom_label_repel(data = label_data,
aes(x = long, y = lat, label = region), size = 3,
max.overlaps = 12)
My code fails on the line
mapdata_x <- map_data('world') %>% filter(region %in% all_districts$region)
Giving the error:
Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function '%in%': object 'region' not found.
How do I define this so that I can get Lesotho as a region?, or if there is an alternative way of achieving this.
Created on 2024-03-29 with reprex v2.0.2