为 stat_sf_coordinates 添加标签 geom_sf returns 错误

Adding label to geom_sf returns error for stat_sf_coordinates

我目前正在尝试向显示县名的美国县地图添加标签。我使用 geom_sf 可视化地图,一切正常。我指定了一些其他的东西,比如填充美学等,它得到了我想要的 plottet。但是如果我尝试通过 geom_sf_label 添加标签,我总是会收到以下错误:stat_sf_coordinates requires the following missing aesthetics: geometry.

这是有效的代码:

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()

我的数据包含美国不同县的交通站点。我按县对它们进行计数,并在分区统计图中将其可视化。

这是我尝试添加标签的方式:

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()

我使用的连接效果很好。只有涉及标签时才会显示上述错误。我也尝试在 geom_sf_label 中添加几何美感,但这也不起作用。 我希望有人能帮助我找到我犯的错误。提前致谢!

我找到了问题的答案。在geom_sf_label命令中定义几何美学后产生的错误可以通过将几何函数定义为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()