r - 格式化多个 geom_sf 图例

标签 r ggplot2 sf

我正在 ggplot 中处理多个 sf 几何图形,并希望以点、线和正方形(对于多边形)的形式显示图例。然而,geom_sf图例结合了我的几何特征(即结合线和点)如下所示:

library(ggplot2)
library(sf)

poly1 <- cbind(lon = c(5, 6, 7, 5), lat = c(52, 53, 51, 52))

poly <- st_sf(st_sfc(st_polygon(list(poly1))))
line <- st_sf(st_sfc(list(st_linestring(cbind(lon = c(5.5, 4.5), lat = c(53.5, 54.5))))))
point <- st_sf(st_sfc(st_point(cbind(lon = 5.5, lat = 52.7))))

ggplot() +
  geom_sf(data = poly, aes(fill = "A")) +
  geom_sf(data = point, aes(colour = "B"), show.legend = "point") +
  geom_sf(data = line, aes(colour = "C"), show.legend = "line") +
  scale_fill_manual(values = c("A" = "yellow")) +
  scale_colour_manual(values = c("B" = "pink", "C" = "purple")) +
  theme_minimal()

enter image description here

我想要三个独立的图例,一个黄色方块、一个粉红色点和下图所示的同一图像上的一条紫色线。只有当我绘制单个几何图形而不是三个的组合时才会出现这种情况。

enter image description here

enter image description here

enter image description here

我查找了类似的主题,但没有一个涉及点几何,即 https://github.com/tidyverse/ggplot2/issues/2460

有人会对此提供任何见解吗?

GitHub 问题:https://github.com/tidyverse/ggplot2/issues/2763

最佳答案

受到@Axeman 评论的启发,this issuethis post ,使用override.aes解决了问题参数在 guide_legend() :

library(ggplot2)
library(sf)

poly1 <- cbind(lon = c(5, 6, 7, 5), lat = c(52, 53, 51, 52))

poly <- st_sf(st_sfc(st_polygon(list(poly1))))
line <- st_sf(st_sfc(list(st_linestring(cbind(lon = c(5.5, 4.5), lat = c(53.5, 54.5))))))
point <- st_sf(st_sfc(st_point(cbind(lon = 5.5, lat = 52.7))))

ggplot() +
  geom_sf(data = poly, aes(fill = "A")) +
  geom_sf(data = point, aes(colour = "B"), show.legend = "point") +
  geom_sf(data = line, aes(colour = "C"), show.legend = "line") +
  scale_fill_manual(values = c("A" = "yellow"), name = NULL,
                    guide = guide_legend(override.aes = list(linetype = "blank", shape = NA))) +
  scale_colour_manual(values = c("B" = "pink", "C" = "purple"), name = NULL,
                      guide = guide_legend(override.aes = list(linetype = c("blank", "solid"), 
                                                               shape = c(16, NA)))) +
  theme_minimal() 

enter image description here

关于r - 格式化多个 geom_sf 图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51371480/

相关文章:

r - 没有 geom 的 ggforce 注释?

r - 无法让 alpha 与 ggplot2::geom_sf 在 sf linestring 对象上一起使用

使用向下应用行时的 R 引用列

r - 在 ggplot2 中绘制累积计数

r - 如何在 R 中将向量分解为连续的组

r-将sf::st_within的输出转换为矢量

r - 如何对齐谷歌地图经度纬度的ggmap CRS

r - geom_area 绘图区域的间隙

r - ggplot2 问题 : Error in FUN(X[[i]], ...) : 未找到对象 'HR'

r - 如何安装 Caret 包?安装时,我收到此消息