将线条图例添加到 geom_sf
Add line legend to geom_sf
我有几个包含各种 public 交通路线的空间形状文件,我想使用 ggplot2
和 sf
库制作地图。这里的问题是我手动为一些特定的路线分配了颜色,但我无法设法为情节添加图例。
知道如何使用 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" )
我知道可以这样做:
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"))
但是,我正在使用多个形状文件,因此我需要使用多个 geom_sf
。另外,我希望图例看起来像线图例,而不是多边形图例。
我们可以在这里使用 geom_sf
中的参数 show.legend
。
ggplot() +
geom_sf(data= simple.lines.sf, aes(colour = as.factor(id)), show.legend = "line")
show.legend
的描述来自 ?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.
我有几个包含各种 public 交通路线的空间形状文件,我想使用 ggplot2
和 sf
库制作地图。这里的问题是我手动为一些特定的路线分配了颜色,但我无法设法为情节添加图例。
知道如何使用 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" )
我知道可以这样做:
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"))
但是,我正在使用多个形状文件,因此我需要使用多个 geom_sf
。另外,我希望图例看起来像线图例,而不是多边形图例。
我们可以在这里使用 geom_sf
中的参数 show.legend
。
ggplot() +
geom_sf(data= simple.lines.sf, aes(colour = as.factor(id)), show.legend = "line")
show.legend
的描述来自 ?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.