[英]How to create a custom legend with ggplot2 and ggarrange?
使用 function ggarrange和 ggplot2 图时,我在创建自定义图例时遇到问题。
我正在制作的当前 plot 是左侧的那个,但我希望图例看起来像右侧的那个:
换句话说,我有一组带有自定义文本的颜色列表,我希望它们都包含在图例中,而不管 plot 中使用的颜色是什么。
我想要的图例颜色存储在 object 图表中:
chart <- structure(list(plotvals = c(0.2, 0.4, 0.6, 0.8, 1), Colour = c(
"#000080", "#87CEFA", "#00FF00", "#FFA500", "#FF0000")), row.names = c(1L,
2L, 3L, 4L, 5L), class = "data.frame")
> chart
plotvals Colour
1 0.2 #000080
2 0.4 #87CEFA
3 0.6 #00FF00
4 0.8 #FFA500
5 1.0 #FF0000
我可以在左侧创建 plot,如下所示:
df <- structure(list(pos = c(82304304L, 82402792L, 82567842L, 82646930L,
82686681L), val = c(0.0336705048361217, 0.0304909014034332, 3.21204387671607,
2.28366271211045, 1.7182850299727), Colour = c("#000080", "#000080",
"#87CEFA", "#00FF00", "#87CEFA")), row.names = c(1L, 2L, 3L,
4L, 5L), class = "data.frame")
> df
pos val Colour
1 82304304 0.0336705 #000080
2 82402792 0.0304909 #000080
3 82567842 3.2120439 #87CEFA
4 82646930 2.2836627 #00FF00
5 82686681 1.7182850 #87CEFA
plot1 <- ggplot(df, aes(pos, rep(1, times = nrow(df)))) +
geom_point(shape = "\u007C", size = 5) +
theme_void()
plot2 <- ggplot(df, aes(pos, val, colour = Colour)) +
geom_point() +
ylim(0, 4) +
theme_bw() +
scale_color_identity(guide = "legend")
plots <- ggarrange(plot1, plot2, heights = c(0.5, 6),
ncol = 1, nrow = 2, align = "v", common.legend = TRUE, legend = "right")
png("plots.png")
plots
dev.off()
如何调整图例,使其成为自定义图例,但仍可与 ggarrange 一起使用?
不确定这是否适用于您的实际情况,但对于示例数据,一种选择是根据您的chart
df 加上一些额外的 hacks 通过guide_legend
设置色标的limits
和labels
,即使用shape
并设置size
:
library(ggplot2)
library(ggpubr)
plot1 <- ggplot(df, aes(pos, rep(1, times = nrow(df)))) +
geom_point(shape = "\u007C", size = 5) +
theme_void()
plot2 <- ggplot(df, aes(pos, val)) +
geom_point(aes(colour = Colour)) +
theme_bw() +
scale_color_identity(
guide = guide_legend(reverse = TRUE, override.aes = list(shape = 15, size = 5)),
limits = chart$Colour, labels = scales::number(chart$plotvals)
) +
scale_fill_manual(values = chart$Colour)
plots <- ggarrange(plot1, plot2,
heights = c(0.5, 6),
ncol = 1, nrow = 2, align = "v", common.legend = TRUE, legend = "right"
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.