如何在patchwork的wrap_plots中仅保留散点图的图例?
合并ggplot2图形时仅保留散点图图例
当使用patchwork合并多个ggplot2图形(包括散点图和直方图)时,默认会保留所有图例,需要仅保留散点图的图例且自动居中,无需手动调整尺寸适配自动化流程。
原复现代码:
library(ggplot2) library(patchwork) plot_histogram <- function() { plot_data <- ggplot(mtcars, aes(x = mpg, fill = factor(am))) + geom_histogram(binwidth = 2, color = "black") + labs(title = "Histo", x = "Miles/gallon", y = "nb cars", fill = "Transmission") + scale_fill_manual(values = c("skyblue", "salmon"), labels = c("Auto", "Man")) + theme_minimal() + theme(legend.position = "bottom") return(plot_data) } plot_scatter <- function() { plot_data <- ggplot(mtcars, aes(x = mpg, y = wt, color = factor(cyl))) + geom_point(size = 3) + labs(title = "Scatterplot", x = "Miles/gallon", y = "weight", color = "Cyl") + theme_minimal() + theme(legend.position = "bottom") return(plot_data) } scatter_plot_left <- plot_scatter() scatter_plot_right <- plot_scatter() histogram_plot <- plot_histogram() combined_plots <- wrap_plots(scatter_plot_left + scatter_plot_right, histogram_plot, nrow = 1, widths = c(3, 1)) + plot_layout(guides = 'collect') & theme(legend.position = "bottom") combined_plots
解决方案
方法1:修改直方图生成函数,直接移除其图例
在plot_histogram函数中设置隐藏图例,合并时就不会收集到它的图例:
plot_histogram <- function() { plot_data <- ggplot(mtcars, aes(x = mpg, fill = factor(am))) + geom_histogram(binwidth = 2, color = "black") + labs(title = "Histo", x = "Miles/gallon", y = "nb cars", fill = "Transmission") + scale_fill_manual(values = c("skyblue", "salmon"), labels = c("Auto", "Man")) + theme_minimal() + theme(legend.position = "none") # 隐藏直方图图例 return(plot_data) }
保持原合并代码不变,plot_layout(guides='collect')会自动收集散点图的图例,并将其居中放置在整个组合图底部,无需手动调整。
方法2:不修改原函数,合并时临时移除直方图的图例
如果不想改动原函数,可以在合并前对直方图对象临时修改,隐藏其图例:
scatter_plot_left <- plot_scatter() scatter_plot_right <- plot_scatter() # 临时隐藏直方图的图例 histogram_plot <- plot_histogram() + theme(legend.position = "none") combined_plots <- wrap_plots(scatter_plot_left + scatter_plot_right, histogram_plot, nrow = 1, widths = c(3, 1)) + plot_layout(guides = 'collect') & theme(legend.position = "bottom") combined_plots
原理说明
- 通过
theme(legend.position = "none")移除直方图的图例后,plot_layout(guides='collect')只会收集散点图的图例。 - patchwork会自动将收集到的图例居中对齐在整个组合图底部,尺寸自适应,完全适配自动化生成流程。
内容的提问来源于stack exchange,提问作者NoNameBoyy
相关产品推荐
相关产品推荐

