ggplot2/ggarrange为手动着色柱状图添加共享自定义图例
实现方案
你只需要在原有代码生成gg_a、gg_b、gg_c三个子图后,新增以下代码生成共享自定义图例再拼接即可,无需修改原有绘图逻辑:
# 加载所需依赖(如已加载可忽略) library(ggplot2) library(ggpubr) library(rstatix) library(reshape2) library(dplyr) # 1. 构造自定义图例映射关系 legend_data <- data.frame( group = c("Label 1", "Label 2"), color = c("#9E0142", "#FDAE61") ) # 2. 生成临时绘图提取目标图例 temp_legend_plot <- ggplot(legend_data, aes(x = 1, y = 1, fill = group)) + geom_col() + scale_fill_manual( name = "", # 可自定义图例标题,不需要则留空 values = c("Label 1" = "#9E0142", "Label 2" = "#FDAE61") ) + theme( legend.position = "bottom", # 图例默认放底部,可改为top/right/left legend.text = element_text(size = 10) ) shared_legend <- get_legend(temp_legend_plot) # 3. 先拼接三个横向子图 plots_row <- ggarrange(gg_a, gg_b, gg_c, ncol = 3, nrow = 1, align = "hv") # 4. 拼接子图和共享图例为最终图形 final_figure <- ggarrange( plots_row, shared_legend, nrow = 2, heights = c(0.9, 0.1) # 可根据显示效果调整子图和图例的高度占比 ) # 输出最终效果 final_figure
如果需要将图例放在右侧,仅需修改最后一步拼接参数即可:
final_figure <- ggarrange( plots_row, shared_legend, ncol = 2, widths = c(0.9, 0.1) )
内容的提问来源于stack exchange,提问作者becbot
相关产品推荐
相关产品推荐

