我的问题结合了之前在 Stackoverflow 上发布的两个单独的问题:向 ggplot 添加多个图例 https://stackoverflow.com/questions/26443371/adding-multiple-legends-to-ggplotii.将线图例添加到 geom_sf https://stackoverflow.com/questions/47996634/add-line-legend-to-geom-sf.
我想添加多个图例ggplot2
(如第一篇文章中所示),但我正在使用sf
。这使得填充美学空间变得复杂。 i 中建议的答案。上面的方法不适用于多种类型的几何图形——我们不能将点和线分配给单个类,然后使用因子。就我而言,我有几个线和点形状文件,并且只想为添加的每个形状文件添加单独的图例条目。
好像不需要调用aes()
, but aes()
或许,这是称呼传奇的唯一方式。
可重现的例子
我想做类似以下的事情(借用(i)),但是without the 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" )