You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为ggarrange组合的多ggplot图形添加统一图例

解决ggplot网格统一底部图例+列标题的问题

我需要生成由ggplot图形组成的网格,每列带标题。目前的方法能保证4个图形尺寸一致且无大量空白,但无法显示图例,希望给整个图形添加一个位于下方的统一图例。当前代码及效果如下:

library(ggplot2)
data=data.frame(x_1 = c(1:5),y_1 =c(1:5)^2,x_2= c(1:5),y_2 =c(1:5)^3,x_3 = c(1:5),y_3 =c(1:5)^4)

plot1<- ggplot(data)+geom_line(aes(x=x_1,y=y_1),col="red")+geom_line(aes(x=x_2,y=y_2),col="blue")+geom_line(aes(x=x_3,y=y_3),col="green")+scale_color_manual(limits = c("a = 2", "a = 3", "a = 4"),values = c("red","blue","green"))

a=ggarrange(plot1, plot1,nrow=2,ncol=1,common.legend = FALSE)
b=ggarrange(plot1,plot1,nrow=2,ncol=1,common.legend = FALSE)
a=annotate_figure(a, top = text_grob("Plots 1",  size = 12))
b=annotate_figure(b, top = text_grob("Plots 2",  size = 12))
c=ggarrange(a, b,nrow=1,ncol=2,common.legend = TRUE)

当前效果:
图形效果


修正方案

核心问题是原代码里没有把颜色映射到变量(直接指定col参数),导致scale_color_manual无法生成有效图例。调整后的代码如下:

library(ggplot2)
library(ggpubr)

# 把宽格式数据转为长格式(ggplot推荐的结构)
data_long <- data.frame(
  x = rep(1:5, 3),
  y = c((1:5)^2, (1:5)^3, (1:5)^4),
  group = rep(c("a = 2", "a = 3", "a = 4"), each = 5)
)

# 生成基础图,将颜色映射到分组变量,同时隐藏单个图的图例
plot1 <- ggplot(data_long, aes(x = x, y = y, color = group)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue", "green")) +
  theme(legend.position = "none")  # 关闭子图自身的图例

# 组合每列的两个子图
col1 <- ggarrange(plot1, plot1, nrow = 2)
col2 <- ggarrange(plot1, plot1, nrow = 2)

# 为每列添加顶部标题
col1_with_title <- annotate_figure(col1, top = text_grob("Plots 1", size = 12))
col2_with_title <- annotate_figure(col2, top = text_grob("Plots 2", size = 12))

# 组合两列,并添加底部统一图例
final_plot <- ggarrange(col1_with_title, col2_with_title,
                        nrow = 1, ncol = 2,
                        common.legend = TRUE,
                        legend = "bottom")  # 指定图例位置在底部

final_plot

关键调整说明

  • 转长格式数据:让分组变量明确,便于ggplot进行颜色映射,这是更规范的用法。
  • 颜色映射到aes内:将color = group放入aes,让ggplot识别这是一个分组美学,从而生成对应的图例。
  • 隐藏子图图例:避免每个子图都显示图例,保证整体整洁。
  • 指定图例位置:通过legend = "bottom"把统一图例放在整个网格的下方,同时common.legend = TRUE确保只生成一份图例。

内容的提问来源于stack exchange,提问作者user18822942

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:35:15