Place labels outside of polygon
23:12 23 Jan 2024

I have created this map: my map

However, I need the labels to sit just outside of the polygons so that the inside includes only the data points. Another alternative would be to color code each polygon and have a legend titled Statistical Areas (and the colors for 909, 910, 911 corresponding). I would also like the y-axis to read as Latitude and the x-axis to read as Longitude.

Below is the script I have used for the formatting. Does anyone know what I need to add to the script to make these alterations?

library(ggplot2)

ggplot(data = stats_shapefile) +
  geom_sf(fill = 'White') +
  geom_sf(data = samples_sf)
  scale_fill_discrete("Statistical Area") +
  geom_sf_text(
    aes(label = Statistica),
    size = 8 / .pt,
    position = "identity"
    )

Based on the suggestion from @Shibaprasad, I tried using the ggrepel package but I got an error and warning:

library(ggrepel)

ggplot(data = stats_shapefile) +
  geom_sf(fill = 'White') +
  geom_sf(data = samples_sf) +
  scale_fill_discrete("Statistical Area") +
  geom_sf_text(aes(label = Statistica), size = 8 / .pt) +
  geom_text_repel(
    nudge_x = ifelse(stats_shapefile$Statistica == 6, 1, 0),
    nudge_y = ifelse(stats_shapefile$Statistica == 6, 8, 0)
    ) 

Error in geom_text_repel():
! Problem while setting up geom.
ℹ Error occurred in the 3rd layer.
Caused by error in compute_geom_1():
! geom_text_repel() requires the following missing aesthetics: x, y, and label.
Run rlang::last_trace() to see where the error occurred.
Warning message:
In st_point_on_surface.sfc(sf::st_zm(x)) :
st_point_on_surface may not give correct results for longitude/latitude data

r ggplot2 geom-sf