【问题标题】:Add multiple legends to ggplot2 when using geom_sf使用 geom_sf 时向 ggplot2 添加多个图例
【发布时间】:2018-02-14 16:20:14
【问题描述】:

我的问题结合了之前在 Stackoverflow 上发布的两个独立问题:i。 Adding multiple legends to ggplot 和 ii。 Add line legend to geom_sf.

我想向ggplot2 添加多个图例(如第一篇文章中所述),但我使用的是sf。这使填充美学空间变得复杂。我建议的答案。以上不适用于多种类型的几何图形——我们不能将点和线分配给单个类然后使用因子。就我而言,我有几个线和点 shapefile,并且只想为添加的每个 shapefile 添加单独的图例条目。

似乎没有必要调用aes(),但aes() 可能是调用图例的唯一方法。

可重现的例子

我想做与以下类似的事情(借用 (i)),但 没有 as.factor 以便我可以单独调用 @ 987654328@:

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

也就是说,更像是:

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

【问题讨论】:

    标签: r plot ggplot2 legend sf


    【解决方案1】:

    我不确定我是否完全理解您想要什么。 在这里,我们将值“A”和“B”映射到颜色 aestetic 以获得图例,然后我们使用 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 ?") 
    

    【讨论】:

    • 谢谢!这正是我想要的——能够强制一种审美,然后再调用它。我没有意识到您可以强制使用这样的常量:“A”和“B”。
    • 如果其他人遇到类似问题并试图弄清楚如何组合图例,这里有一些有用的链接:Combine legends for color and shape into a single legend
    • 虽然,现在我收到以下错误:Error: length(rows) == 1 is not TRUE 这似乎来自调用 show.legend = "line" - 如果我排除 show.legend 没有问题,除了图例是填充不是一条线。
    • 我提供的代码ggplot2_2.2.1.9000sf_0.5-4没有任何错误消息...
    • 好的——重启后我也没有。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多