未指定美学时用 geom_sf 绘制图例

Draw legend with geom_sf when no aesthetic is specified

使用 ggplot/geom_sf 绘制地图时,任何映射到美学的图层都会在图例中表示。我也知道使用 show.legend = ... 可用于强制图例表示和操纵所使用的符号系统(点、线、多边形)。然而,当绘制简单的对象而不需要进一步将它们映射到美学时,即使用 colour/fill 来显示附加信息,没有给出图例条目。使用 show.legend = TRUE 时似乎也是如此。我在 GitHub: https://github.com/tidyverse/ggplot2/issues/3636 上发现了这个问题。我不太确定,问的人是否理解正确,但似乎没有一个好的答案。所以,使用他的代码:

library(ggplot2)
library(sf)

nc <- st_read(system.file("shape/nc.shp", package = "sf"))
ggplot(nc) + geom_sf(show.legend = TRUE)

无法生成图例。我希望图例简单地显示一条与地图中颜色相同的线,并为该层命名。我可以使用此解决方法添加图例:

ggplot() +
  geom_sf(aes(fill = "US State borders"), nc, show.legend = "line")

但是,这现在改变了绘图层的颜色。好的,让我们尝试指定一种颜色:

ggplot() +
  geom_sf(aes(fill = "US State borders"), nc, fill = "grey", show.legend = "line")

哎呀,图例又丢了,可能是因为我现在指定了两次fill。使用 ggplot/geom_sf 真的不可能吗?

如果我理解正确的话,如果你在 scale_fill_manual():

中指定填充颜色,它应该可以工作
  ggplot() +
    geom_sf(aes(fill = "US State borders"), nc, show.legend = "line") +
    scale_fill_manual(values = 'grey') +
    labs(fill = '') # removing legend title