给geom_sf添加线图例

6

我有几个包含不同公共交通路线的空间形状文件,希望使用ggplot2sf库制作地图。问题在于我手动为一些特定路线分配颜色,但是我无法将图例添加到图表中。

有没有想法如何使用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来处理多个形状文件。此外,我希望图例显示为一条线的形式,而不是一个多边形的图例。

1个回答

10
我们可以在这里使用来自geom_sf的参数show.legend
ggplot() + 
 geom_sf(data= simple.lines.sf, aes(colour = as.factor(id)), show.legend = "line")

show.legend的说明来自于?geom_sf

逻辑型。是否将该图层包含在图例中?默认情况下,如果映射任何美学属性,则为NA,会被包含在图例中。FALSE永远不会被包含,而TRUE总是会被包含。 您还可以将其设置为“polygon”、“line”和“point”之一,以覆盖默认图例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接