I am working to create a map in ggplot2 using the geom_sf() function. The data for the map is from a KML file (downloaded from GoogleEarth), so when I read that into R, the lat/longs for each datapoint are in a combined 'geometry' column rather than individual lat/long columns. I need to add labels for each point onto my map, but since everything is in the 'geometry' column, I do not have the proper inputs for the aes() function, when it asks for 'x' and 'y' values.
My data is currently arranged like this:
Name Description Island BeachName Density geometry
1 C28 St. Croix Boiler Bay B POINT Z (-64.57273 17.75859 0)
2 C27 St. Croix Brown Bay A POINT Z (-64.57583 17.75935 0)
3 C39 St. Croix Buck Island Reef NM C POINT Z (-64.62571 17.78738 0)
4 C1 St. Croix Sandy Point NWR C POINT Z (-64.89964 17.67955 0)
5 C10 St. Croix Rainbow Beach A POINT Z (-64.88799 17.72994 0)
I have tried using geom_text():
stc_plot <- ggplot() +
geom_sf(data = stc_land, color = "grey40", fill = "grey80") +
geom_sf(data = stcdens, aes(size = Density)) +
geom_text(data = stcdens, aes(label = Name)) +
labs(size = "Nesting Activities per Year") +
scale_size_discrete(labels = c("<25", "25-100", "100-500")) +
theme_classic() +
theme(legend.position = "bottom")
And I get an error:
Error in `check_required_aesthetics()`:
! geom_text requires the following missing aesthetics: x and y
Is there a way to get the geometry column to be read out for labels? Or would I need to split that column so that the lat/longs are separate? The geometry column has worked fine for all other aspects of creating this map, its just the labeling that is giving me trouble...
You need to substitute your ggplot2::geom_text() for ggplot2::geom_sf_text() - the sf part is important.
For an example consider this plot of 3 semi random North Carolina cities (did I mention I <3 the nc.shp file?)
library(sf)
library(ggplot2)
shape <- st_read(system.file("shape/nc.shp", package="sf")) # included with sf package
cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
x = c(-78.633333, -79.819444, -77.912222),
y = c(35.766667, 36.08, 34.223333),
population = c("high", "medium","low")) %>%
st_as_sf(coords = c("x", "y"), crs = 4326)
ggplot() +
geom_sf(data = shape, fill = NA) +
geom_sf_text(data = cities, aes(label = name))

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