Arcticweasel
Arcticweasel

Reputation: 43

Adding label to geom_sf returns error for stat_sf_coordinates

I'm currently trying to add labels to a map of US counties, that display the county name. I visualized the map using geom_sf and everything works out fine. I specified some other things like the fill aesthetic etc. and it gets plottet like I wanted it to. But if I try to add labels via geom_sf_label, I always get the following error: stat_sf_coordinates requires the following missing aesthetics: geometry.

Here is the code that works:

df %>%
  group_by(county_fips)%>%
  count()%>%
  full_join(geo_data, by = c("county_fips" = "fips")) %>%
  ggplot(aes(fill = n))+
  geom_sf(aes(geometry = geometry))+
  scale_fill_continuous(low = "antiquewhite2", high = "palevioletred4", guide = "colorbar")+
  theme_void()

My data cointains traffic stops in different counties in the US. I count them by county and visualize that in a choropleth map.

Here is how I tried to add the label:

df %>%
  group_by(county_fips)%>%
  count()%>%
  full_join(geo_data, by = c("county_fips" = "fips")) %>%
  ggplot(aes(fill = n))+
  geom_sf(aes(geometry = geometry))+
  geom_sf_label(aes(label = paste0(ID)))+
  scale_fill_continuous(low = "antiquewhite2", high = "palevioletred4", guide = "colorbar")+
  theme_void()

The join I used works out just fine. Only when it comes to the labels the above error is displayed. I tried to add the geometry aesthetic in geom_sf_label, too, but that won't work either. I hope someone can help me to find the mistake I made. Thank you in advance!

Upvotes: 2

Views: 4254

Answers (1)

Arcticweasel
Arcticweasel

Reputation: 43

I found an answer to my question. The error that is produced after defining the geometry aesthetic in the geom_sf_label command can be repaired by defining the geometry function to be st_centroid.

df %>%
  group_by(county_fips, county_name)%>%
  count()%>%
  full_join(geo_data, by = c("county_fips" = "fips")) %>%
  ggplot(aes(fill = n))+
  geom_sf(aes(geometry = geometry))+
  geom_sf_text(aes(label = ID, geometry = geometry), fun.geometry = st_centroid)+
  scale_fill_continuous(low = "antiquewhite2", high = "palevioletred4", guide = "colorbar")+
  theme_void()

Upvotes: 2

Related Questions