[英]Combine fill and color legend in ggplot
我发现了一些与我的问题类似的问题,但没有一个真正适合。 我有 4 个数据列我想要 plot,3 个作为行,1 个作为区域。
我想将生成的 Plot 的图例浓缩成一个整齐的 2 行 2 列设置,但我似乎不知道如何。 示例代码:
library(tidyverse)
#Random Data
data <- tibble(X=1:50,
A=sample(seq(5, 6, 0.1), 50, replace = TRUE),
B=sample(seq(4, 5, 0.1), 50, replace = TRUE),
C=sample(seq(3, 4, 0.1), 50, replace = TRUE),
D=sample(seq(1, 3, 0.5), 50, replace = TRUE))
ggplot(data, aes(x=X)) +
geom_area(aes(y=D, fill='Dataset4'), alpha=0.5) +
geom_line(aes(y=A, color='Dataset1')) +
geom_line(aes(y=B, color='Dataset2')) +
geom_line(aes(y=C, color='Dataset3')) +
ylab("")+
guides(fill=guide_legend(nrow=2, order=2),
color=guide_legend(nrow=2, order=1))
结果图:
我想让四个图例条目以 2x2 方向排列,这可能吗?
您可以通过使用具有颜色和填充美感的比例来做到这一点。 棘手的一点是让图例知道什么应该画成一条线,什么应该画成一个多边形,对此我没有自动解决方案。 下面的手动解决方案有效,但如果您使用不同的比例,则必须用另一种颜色替换第 4 次填充。
library(ggplot2)
library(tibble)
#Random Data
data <- tibble(X=1:50,
A=sample(seq(5, 6, 0.1), 50, replace = TRUE),
B=sample(seq(4, 5, 0.1), 50, replace = TRUE),
C=sample(seq(3, 4, 0.1), 50, replace = TRUE),
D=sample(seq(1, 3, 0.5), 50, replace = TRUE))
ggplot(data, aes(x=X)) +
geom_area(aes(y=D, fill='Dataset4'), alpha=0.5) +
geom_line(aes(y=A, color='Dataset1')) +
geom_line(aes(y=B, color='Dataset2')) +
geom_line(aes(y=C, color='Dataset3')) +
scale_colour_discrete(
name = "",
aesthetics = c("colour", "fill"),
guide = guide_legend(
nrow = 2, override.aes = list(
linetype = c(1, 1, 1, 0),
fill = c(NA, NA, NA, scales::hue_pal()(4)[4])
)
)
) +
ylab("")
#> Warning: Duplicated override.aes is ignored.
由代表 package (v2.0.0) 于 2022 年 8 月 31 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.