【问题标题】:Adding labels to map data in R在 R 中添加标签以映射数据
【发布时间】:2021-11-14 16:07:35
【问题描述】:

因此,基于this post,我使用 ggplot 创建了纽约市行政区的地图

我有一个看起来像这样的数据集,称为boroughs_personal

borough    count
Brooklyn     211
Manhattan     12
Queens         1

所以我将它加入到地图数据中,类似于上面的帖子,它就像一个梦一样工作。

# download and extract data
bb <- getbb("New York City, New York")

boundaries <- opq(bbox = bb) %>% 
  add_osm_feature(key = "boundary", value = "administrative") %>% 
  osmdata_sf() %>% 
  unname_osmdata_sf()

boroughs <- boundaries[["osm_multipolygons"]] %>% 
  filter(name %in% c("Manhattan", "The Bronx", "Brooklyn", "Queens", "Staten Island")) %>% 
  left_join(boroughs_personal , by = c('name' = 'borough'))

ggplot() +
  geom_sf(data = boroughs, aes(fill = count))+
  ##guides(fill=FALSE) + 
  scale_fill_continuous(low = "lightblue", high = "darkblue")+
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(),
        axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) + 
  ggtitle('New York Boroughs ') 

但我需要将count 变量的标签添加到每个行政区。我该怎么做???

【问题讨论】:

  • geom_sf_text(aes(label = count), colour = "white")我试过这个但没有用@camille
  • 为什么?发生什么了?无需安装和下载所有内容即可查看您正在查看的内容会很有帮助
  • @camille 这是错误Don't know how to automatically pick scale for object of type function. Defaulting to continuous. Error: Aesthetics must be valid data columns. Problematic aesthetic(s): label = count. Did you mistype the name of a data column or forget to add after_stat()?

标签: r ggplot2 label sf


【解决方案1】:

考虑将 dataaes() 声明从 geom_sf 移动到主 ggplot 函数。然后geom_sf_label() 将知道在哪里查找您的数据对象。

另一种方法是在每个 geom_sf_* 调用中同时包含 data 和 aes - 但这是不必要的,因为标签和填充都基于相同的数据对象。

  ggplot(data = boroughs, aes(fill = count, 
                            label = count)) +
  geom_sf() +
  geom_sf_label(fill = "white",  # override the fill from aes()
                fun.geometry = sf::st_centroid) + # make Manhattan behave itself
  scale_fill_continuous(low = "lightblue", 
                        high = "darkblue") +
  theme(axis.title=element_blank(), 
        axis.text=element_blank(), 
        axis.ticks=element_blank()) + 
  ggtitle('New York Boroughs ') 

【讨论】:

  • 这是关闭!我唯一的问题,有没有办法让 12 更好地进入曼哈顿?相对于离得这么远?
  • 我也注意到了,但由于标签的放置确实是一个单独的问题,我不想将它结合起来;但既然你提到它......请参阅更新的代码和图片。供参考:默认标注放置函数为sf::st_point_on_surface(),保证放置在多边形内;在这种情况下,它不适用于曼哈顿,因此sf::st_centroid() - 将标签放置在多边形的中心 - 更合适。如果失败,您可以随时使用 nudge_x 和 nudge_y 进行微调。
  • 再想一想:默认标签放置功能选择埃利斯岛作为曼哈顿的“表面点”,这有点甜...:D
猜你喜欢
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多