我正在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()
Run Code Online (Sandbox Code Playgroud)
我想要三个单独的图例,一个黄色正方形,一个粉红色的点和一条紫色的线,如下图所示。只有当我绘制单个几何图形而不是三个图形的组合时,才是这种情况。
我查找了类似的主题,但是它们都没有涉及点几何,即https://github.com/tidyverse/ggplot2/issues/2460
有人会对此提供任何见解吗?
GitHub问题:https : //github.com/tidyverse/ggplot2/issues/2763
受到@Axeman的评论,本期和本帖的启发,使用以下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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
879 次 |
| 最近记录: |