使用 geom_sf 时向 ggplot2 添加多个图例

Add multiple legends to ggplot2 when using geom_sf

我的问题结合了两个独立的问题 post之前在 Whosebug 上讨论过:i。 Adding multiple legends to ggplot and ii. .

我想向 ggplot2 添加多个图例(如第一个 post),但我正在使用 sf。这使填充美学变得复杂 space。 i 中建议的答案。以上不适用于多种类型的几何形状——我们不能将点和线分配给单个 class 然后使用因子。在我的例子中,我有几个线和点 shapefile,只是想为每个添加的 shapefile 添加一个单独的图例条目。

似乎没有必要调用aes(),但aes()可能是调用图例的唯一方法。

可重现的例子

我想做类似下面的事情(借用(i)),但是没有 as.factor 这样我就可以单独调用 geom_sf:

library(sf)
library(ggplot2)

# reproducible data
lon<-c(5.121420, 6.566502, 4.895168, 7.626135)
lat<-c(52.09074, 53.21938, 52.37022, 51.96066)
cities<-c('utrecht','groningen','amsterdam','munster')
size<-c(300,500,1000,50)

xy.cities<-data.frame(lon,lat,cities,size)

# line example
line1 <- st_linestring(as.matrix(xy.cities[1:2,1:2]))
line2 <- st_linestring(as.matrix(xy.cities[3:4,1:2]))

lines.sfc <- st_sfc(list(line1,line2))
simple.lines.sf <- st_sf(id=1:2,size=c(10,50),geometry=lines.sfc)

ggplot() + 
 geom_sf(data= simple.lines.sf, aes(colour = as.factor(id)), show.legend = "line")

也就是说,更像是:

ggplot() + 
 geom_sf(data= dataset1, color="red" ) +
 geom_sf(data= dataset2, color="blue" )

我不确定我是否完全理解您想要什么。 在这里,我们将值 "A" 和 "B" 映射到颜色 aestetic 以获得图例,然后我们使用 scale_color_manual

自定义颜色
dataset1 <- st_sf(st_sfc(list(line1)))
dataset2 <- st_sf(st_sfc(list(line2)))

ggplot() + 
    geom_sf(data= dataset1, aes(color="A"), show.legend = "line") +
    geom_sf(data= dataset2, aes(color="B"), show.legend = "line") +
    scale_color_manual(values = c("A" = "red", "B" = "blue"), 
                       labels = c("Line1", "Line2"),
                       name = "Which line ?")