本文介绍了将行图例添加到geom_sf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一对具有各种公共交通路线的空间形状文件,我想使用 ggplot2 和 sf 库。这里的问题是,我手动分配颜色到几个特定的​​路线,但我无法设法添加图例的情节。 有关如何使用 geom_sf ? 可重复的例子 库(sf)库(ggplot2) #可再现数据 lon< -c(5.121420,6.566502,4.895168,7.626135) lat 个城市 size< -c(300,500,1000,50) xy.cities< -data.frame( lon,lat,cities,size) #线示例 line1< - st_linestring(as.matrix(xy.cities [1:2,1:2])) line2 lines.sfc< - st_sfc(list(line1,line2)) simple.lines.sf< - st_sf(id = 1:2,size = c(10,50),geometry = lines.sfc) #plot ggplot() + geom_sf(data = subset(simple.lines.sf,id == 1),color =red)+ geom_sf(data = subset(simple.lines.sf,id == 2 ),color =blue) 我知道可以这样做: ggplot()+ geom_sf(data = subset(simple.lines.sf,id> 0),aes(color =因子(id)))+ scale_color_manual(values = c(red,blue), labels = c(route 1,route 2)) 然而,我正在处理多个形状文件,所以我需要使用多个 geom_sf 。另外,我希望图例看起来像是一个线条图例,而不是多边形图例。解决方案我们可以使用参数 show.legend 从 geom_sf 这里。 ggplot()+ geom_sf(data = simple.lines.sf,aes(color = as.factor( 显示的描述show .legend from ?geom_sf 逻辑。该图层是否应该包含在图例中? NA(默认值)包括是否映射任何美学。 FALSE从不包含,并且TRUE始终包含。 您也可以将其设置为多边形,线条和点中的一个以覆盖默认图例。 I have a couple spatial shape files with various public transport routes and I would like to make a map using ggplot2 and sf libraries. The issue here is that I manually assign colors to a few specific routes but I couldn't manage to add a legend to the plot.Any idea on how to do this using geom_sf ?Reproducible examplelibrary(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)# plot ggplot() + geom_sf(data= subset(simple.lines.sf, id==1), color="red" ) + geom_sf(data= subset(simple.lines.sf, id==2), color="blue" )I know it would be possible to do something like this: ggplot() + geom_sf(data= subset(simple.lines.sf, id>0), aes(color=factor(id)) ) + scale_color_manual(values=c("red", "blue"), labels=c("route 1", "route 2"))However, I'm working with more than one shape file so I need to use more than one geom_sf. Also, I would like the legend to look a line legend, not a polygon legend. 解决方案 We can use the argument show.legend from geom_sf here. ggplot() + geom_sf(data= simple.lines.sf, aes(colour = as.factor(id)), show.legend = "line")Description of show.legend from ?geom_sf logical. Should this layer be included in the legends? NA, the default, includes if any aesthetics are mapped. FALSE never includes, and TRUE always includes. You can also set this to one of "polygon", "line", and "point" to override the default legend. 这篇关于将行图例添加到geom_sf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 20:45
查看更多