Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

r - Add line legend to geom_sf

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 example

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

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

enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...