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

如何在ggpairs矩阵图空白面板添加回归线颜色图例?

给GGpairs回归矩阵图添加统一图例

要解决你的问题,核心是把**颜色映射到ggplot的美学属性(aes)**而非直接硬编码颜色,再将统一图例放置到ggpairs上半部分的空白区域。以下是分步修改方案:

1. 重构plot_models函数,启用颜色映射

原来的代码直接给每个geom_smooth指定color参数,这不会触发图例生成。我们需要将颜色映射到aes(color = "模型名称"),再用scale_color_manual绑定颜色和标签:

plot_models <- function(data, mapping, data2) {
  cb_palette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
  
  # 定义模型与颜色的对应关系
  model_colors <- list(
    "无离群点OLS" = cb_palette[3],
    "含离群点OLS" = cb_palette[7],
    "稳健RLM" = cb_palette[4],
    "稳健LMrob" = cb_palette[1]
  )
  
  plt <- ggplot(data = data, mapping = mapping) +
    geom_point() +
    theme_bw() +
    # 每个模型的颜色映射到aes的color参数,触发图例生成
    geom_smooth(method = lm, formula = y ~ x, data = data2, aes(color = "无离群点OLS"), se = FALSE) +
    geom_smooth(method = lm, formula = y ~ x, aes(color = "含离群点OLS"), se = FALSE) +
    geom_smooth(method = rlm, formula = y ~ x, aes(color = "稳健RLM"), se = FALSE) +
    geom_smooth(method = lmrob, formula = y ~ x, aes(color = "稳健LMrob"), se = FALSE) +
    # 手动指定颜色和图例显示标签
    scale_color_manual(values = model_colors) +
    # 隐藏子图自带的图例,我们要统一放一个全局图例
    theme(legend.position = "none")
  
  plt
}

2. 创建单独的全局图例面板

我们需要生成一个只包含图例的ggplot对象,用来填充ggpairs的空白区域:

# 先安装cowplot(如果没装过)
# install.packages("cowplot")

create_legend <- function() {
  cb_palette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
  model_colors <- list(
    "无离群点OLS" = cb_palette[3],
    "含离群点OLS" = cb_palette[7],
    "稳健RLM" = cb_palette[4],
    "稳健LMrob" = cb_palette[1]
  )
  
  # 生成仅含图例的空图
  legend_plot <- ggplot(data.frame(), aes(x = 1, y = 1)) +
    geom_blank() +
    scale_color_manual(values = model_colors, name = "回归模型") +
    theme(
      legend.position = "center",
      panel.background = element_blank(),
      axis.text = element_blank(),
      axis.title = element_blank(),
      axis.ticks = element_blank()
    )
  
  # 提取图例并转换为可插入的ggplot对象
  legend <- cowplot::get_legend(legend_plot)
  ggplot() +
    annotation_custom(grob = legend) +
    theme_void()
}

3. 将图例插入到ggpairs的空白面板

生成ggpairs对象后,用getPlot和putPlot方法把图例放到上半部分的空白位置(比如第一行第二列):

# 生成原始ggpairs图
g <- ggpairs(df_contamin, columns = 1:4,
             lower = list(continuous = wrap(plot_models, data2 = df)),
             diag = list(continuous = "blankDiag"),
             upper = list(continuous = "blank"))

# 创建图例面板
legend_panel <- create_legend()

# 将图例插入到指定空白面板(位置:第1行第2列,索引从1开始)
g <- putPlot(g, legend_panel, row = 1, col = 2)

# 执行原有修剪逻辑
gr <- trim_gg(g)
print(gr)

关键说明

  • 通过aes(color = "模型名称")让ggplot识别需要生成图例的类别,再用scale_color_manual绑定颜色和显示名称。
  • 隐藏子图自带的图例避免重复,生成单独的全局图例插入到空白区域。
  • 你可以调整putPlot的row和col参数,把图例放到上半部分任意空白位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:13:46