我正在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()
在下面显示的同一张图片上,我想要三个单独的图例,一个黄色的正方形,一个粉红色的点和一条紫色的线。只有当我绘制单个几何图形而不是三个图形的组合时,这种情况才会出现。
我查找了类似的主题,但是它们都没有涉及点几何,即https://github.com/tidyverse/ggplot2/issues/2460
有人会对此提供任何见识吗?
答案 0 :(得分:4)
受到@Axeman,this issue和this 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()
答案 1 :(得分:3)
我知道如何分隔图例,因为您两次绘制颜色,所以它们现在才合并在一起。通过将形状映射到这些点并设置颜色,您可以解决此问题:
ggplot() +
geom_sf(data = poly, aes(fill = "A")) +
geom_sf(data = point, aes(colour = "B"), show.legend = "point") +
geom_sf(data = line, aes(shape = "C"), show.legend = "line", color = 'purple') +
scale_fill_manual(name = NULL, values = c("A" = "yellow")) +
scale_colour_manual(name = NULL, values = c("B" = "pink")) +
scale_shape_discrete(
name = NULL,
guide = guide_legend(override.aes = list(color = 'purple'))) +
theme_minimal()
但是:点和线仍在所有三个图例中显示。我认为他们不应该!也许您可以解决github问题。