将行图例添加到geom_sf

问题描述 投票:2回答:1

我有几个空间形状文件与各种公共交通路线,我想使用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" )

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。此外,我希望图例看起来是一个线条图例,而不是多边形图例。

r plot ggplot2 sf
1个回答
5
投票

我们可以在这里使用来自show.legendgeom_sf参数。

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”之一以覆盖默认图例。

© www.soinside.com 2019 - 2024. All rights reserved.