在 R 中向地图数据添加标签

Joh*_*mas 1 label r ggplot2 r-sf

因此,根据这篇文章,我使用 ggplot 创建了纽约行政区的地图

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

borough    count
Brooklyn     211
Manhattan     12
Queens         1
Run Code Online (Sandbox Code Playgroud)

因此,我将其加入到地图数据中,与上面的帖子类似,它就像一个梦想。

# 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 ') 
Run Code Online (Sandbox Code Playgroud)

但我需要将变量的标签添加count到每个行政区。我怎样才能做到这一点???

Jin*_*cko 6

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

另一种方法是在每个 geom_sf_* 调用中同时包含数据和 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 ') 
Run Code Online (Sandbox Code Playgroud)

纽约有标签,曼哈顿表现得很好