我有一张 map ,我试图将其添加到图例中,其中包含 2 个填充多边形和 1 个多边形,但只有轮廓轮廓(仅由虚线表示)。
library(sf);library(ggplot)
# point
p <- rbind(c(1,2), c(2,1), c(3,2), c(3.5,3.5), c(3.4,3.6), c(3.9,1.4))
(mp <- st_multipoint(p))
p1 <- rbind(c(0,0), c(1,0), c(3,2), c(2,4), c(1,4), c(0,0))
p2 <- rbind(c(1,1), c(1,2), c(2,2), c(1,1))
pol <-st_polygon(list(p1,p2))
p3 <- rbind(c(3,0), c(4,0), c(4,1), c(3,1), c(3,0))
p4 <- rbind(c(3.3,0.3), c(3.8,0.3), c(3.8,0.8), c(3.3,0.8), c(3.3,0.3))[5:1,]
p5 <- rbind(c(3,3), c(4,2), c(4,3), c(3,3))
(mpol1 <- st_multipolygon(list(list(p3))))
(mpol2 <- st_multipolygon(list(list(p4))))
(mpol3 <- st_multipolygon(list(list(p5))))
ggplot(mp, aes(geometry = geometry)) +
geom_sf(data = pol, aes(geometry = geometry), inherit.aes = FALSE) +
# Add the points
geom_sf(data = mpol1, alpha = 0.5, aes(geometry = geometry, colour = "grey90", fill = "grey90"), size = 0.05) +
geom_sf(data = mpol2, alpha = 0.5, aes(geometry = geometry, colour = "grey20", fill = "grey20"), size = 0.05) +
geom_sf(data = mpol3, alpha = 0.5, aes(geometry = geometry,colour = "grey30", fill=NA), size = 0.8, linetype = "dotted") +
scale_color_manual(values = c(alpha("grey90",.5),alpha("grey20",.5),alpha("grey30",.5)), labels = c("item1", "item2","item3"), name="My Leg. hurts") +
scale_fill_manual( values = c(alpha("grey90",.5),alpha("grey20",.5),NA), labels = c("item1", "item2","item3"), name="My Leg. hurts") +
theme_bw()+
theme(legend.key = element_rect(fill = NA),
legend.background = element_rect(fill = NA),
legend.text = element_text(size = 12),
legend.title = element_text(size = 12,face='bold'))
给予
但我想要这个:
如何实现?
最佳答案
详细阐述 Ian Campbell 之前的回答:
考虑这段代码(我唯一添加的是 show.legend = 'line'
在最后一个 geom_sf()
调用中)
ggplot(mp, aes(geometry = geometry)) +
geom_sf(data = pol, aes(geometry = geometry), inherit.aes = FALSE) +
# Add the points
geom_sf(data = mpol1, alpha = 0.5, aes(geometry = geometry, colour = "grey90", fill = "grey90"), size = 0.05) +
geom_sf(data = mpol2, alpha = 0.5, aes(geometry = geometry, colour = "grey20", fill = "grey20"), size = 0.05) +
geom_sf(data = mpol3, alpha = 0.5, aes(geometry = geometry,colour = "grey30", fill=NA), size = 0.8, linetype = "dotted", show.legend = 'line') +
scale_color_manual(values = c(alpha("grey90",.5),alpha("grey20",.5),alpha("grey30",.5)), labels = c("item1", "item2","item3")) +
scale_fill_manual( values = c(alpha("grey90",.5),alpha("grey20",.5),NA), labels = c("item1", "item2","item3"), guide = FALSE) +
theme_bw()+
theme(legend.key = element_rect(fill = NA),
legend.background = element_rect(fill = NA),
legend.text = element_text(size = 12),
legend.title = element_text(size = 12,face='bold')) +
guides(color = guide_legend(override.aes =
list(color=c(NA,NA,"grey20"),
fill=c("grey90","grey20","white"),
linetype = c("dotted")))) +
labs(color = "My Leg. hurts")
关于r - 在 R ggplot 图例中混合颜色、填充和线型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67908675/