首页 > 解决方案 > 向 geom_sf 添加标签会返回 stat_sf_coordinates 的错误

问题描述

我目前正在尝试向显示县名的美国县地图添加标签。我使用可视化地图geom_sf,一切正常。我指定了一些其他的东西,比如填充美学等。它得到了我想要的情节。但是如果我尝试通过添加标签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 中添加几何美学,但这也不起作用。我希望有人能帮助我找出我犯的错误。先感谢您!

标签: rggplot2labelsf

解决方案


我找到了我的问题的答案。在命令中定义几何美学后产生的错误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()

推荐阅读