【发布时间】:2018-02-14 16:20:14
【问题描述】:
我的问题结合了之前在 Stackoverflow 上发布的两个独立问题:i。 Adding multiple legends to ggplot 和 ii。 Add line legend to geom_sf.
我想向ggplot2 添加多个图例(如第一篇文章中所述),但我使用的是sf。这使填充美学空间变得复杂。我建议的答案。以上不适用于多种类型的几何图形——我们不能将点和线分配给单个类然后使用因子。就我而言,我有几个线和点 shapefile,并且只想为添加的每个 shapefile 添加单独的图例条目。
似乎没有必要调用aes(),但aes() 可能是调用图例的唯一方法。
可重现的例子
我想做与以下类似的事情(借用 (i)),但 没有 as.factor 以便我可以单独调用 @ 987654328@:
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" )
【问题讨论】: