gpt4 book ai didi

r - 将线图例添加到 geom_sf

转载 作者:行者123 更新时间:2023-12-03 04:48:38 24 4
gpt4 key购买 nike

我有几个包含各种公共(public)交通路线的空间形状文件,我想使用 ggplot2 和 sf 库制作 map 。这里的问题是我手动为一些特定路线分配颜色,但我无法设法向绘图添加图例。

知道如何使用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)

# plot
ggplot() +
geom_sf(data= subset(simple.lines.sf, id==1), color="red" ) +
geom_sf(data= subset(simple.lines.sf, id==2), color="blue" )

enter image description here

我知道可以做这样的事情:

  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"))

enter image description here

但是,我正在使用多个形状文件,因此我需要使用多个 geom_sf。另外,我希望图例看起来是线图例,而不是多边形图例。

最佳答案

我们可以在这里使用geom_sf中的show.legend参数。

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

来自?geom_sfshow.legend的描述

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.

关于r - 将线图例添加到 geom_sf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com