使用geom_sf时,将多个图例添加到ggplot2 [英] Add multiple legends to ggplot2 when using geom_sf

查看:829
本文介绍了使用geom_sf时,将多个图例添加到ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题结合了Stackoverflow上发布的两个单独问题:i。


My question combines two separate issues posted on before on Stackoverflow: i. Adding multiple legends to ggplot and ii. Add line legend to geom_sf.

I would like to add multiple legends to ggplot2 (as in the first post), but am using sf. This complicates filling up the aesthetic space. The answer suggested in i. above does not work well with multiple types of geometries -- we cannot assign points and lines to a single class and then use factors. In my case, I have several line and point shapefiles, and simply want to add a separate legend entry for each shapefile added.

There seems to be no need to invoke aes(), but aes() may be the only way to call a legend.

Reproducible example

I would like to do something similar to the following (borrowing from (i)), but without the as.factor so that I could have separate calls of 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)

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

That is, something more like:

ggplot() + 
 geom_sf(data= dataset1, color="red" ) +
 geom_sf(data= dataset2, color="blue" )

解决方案

I'm not certain that I understand exactly what you want. Here we map values "A" and "B" to the color aestetic in order to obtain a legend and then we customize the colors with scale_color_manual

dataset1 <- st_sf(st_sfc(list(line1)))
dataset2 <- st_sf(st_sfc(list(line2)))

ggplot() + 
    geom_sf(data= dataset1, aes(color="A"), show.legend = "line") +
    geom_sf(data= dataset2, aes(color="B"), show.legend = "line") +
    scale_color_manual(values = c("A" = "red", "B" = "blue"), 
                       labels = c("Line1", "Line2"),
                       name = "Which line ?") 

这篇关于使用geom_sf时,将多个图例添加到ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆