I'm trying to draw map. Is there a way to write the name of the cities outside their borders? Looking for an answer i've found the package ggrepel
, but it seems that it has not been implemented also for geographical maps, indeed if I write
right_join(prov2022, dataset, by = "COD_PROV") %>%
ggplot(aes(fill = `real wage`))+
geom_sf(data = ~ subset(., COD_REG == 7 | COD_REG >= 1 & COD_REG <= 3)) +
theme_void() +
theme(legend.title=element_blank())+
geom_sf_text(data = ~ subset(., COD_REG == 7 ), aes(label = city_name), size = 3) +
scale_fill_gradientn(colors = c( "#FFFFFF","#FFFF00", "#FF0000", "#000000")) +
geom_blank()+
geom_sf_text_repel(aes(label = city_name))
R answers
Error in geom_sf_text_repel(aes(label = city_name)) :
could not find function "geom_sf_text_repel"
Do you know any other way shift the label city_name
from within the borders to the outside ?
You can use nudge_x
and nudge_y
inside geom_sf_text
to move the labels an arbitrary amount:
library(ggplot2)
ggplot(df) +
geom_sf(fill = "white") +
geom_sf_text(aes(label = lab), size = 5, nudge_x = 0.05, nudge_y = 0.05)
If you prefer to control the exact position of each label, these parameters take vectorized inputs:
ggplot(df) +
geom_sf(fill = "white") +
geom_sf_text(aes(label = lab), size = 5,
nudge_x = c(0, -0.05, 0.05),
nudge_y = c(0, -0.05, 0.05))
Data used
library(sf)
df <- st_polygon(list(cbind(c(0, 1, 1, 0, 0), c(0, 0, 1, 1, 0)))) |>
list(st_point(c(0.25, 0.25)), st_point(c(0.75, 0.75))) |>
st_sfc(crs = "WGS84") |>
st_as_sf() |>
within(lab <- c("", "City 1", "City 2"))