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

ggplot2叠加分组回归与新样本图层时图例异常问题求助

解决ggplot2叠加图层后新样本图例不显示的问题

问题分析

叠加训练模型图层(含回归线、置信区间、训练样本)与新样本图层时,新样本图例不显示,本质是新样本的视觉属性(颜色/形状)与训练模型的映射共用了同一套刻度系统,新样本的类别不在原有刻度范围内;使用ggnewscale时出现多个图例,通常是因为未正确开启新刻度或重复设置映射。

解决方案

以下用模拟数据演示两种可行的解决方法:

1. 构造模拟数据

library(ggplot2)
library(dplyr)

# 训练数据:3个回归模型的样本
train_data <- expand.grid(model = c("Model1", "Model2", "Model3"),
                          x = seq(0, 10, length.out = 50)) %>%
  mutate(y = case_when(
    model == "Model1" ~ 2 + 0.8*x + rnorm(n(), 0, 1),
    model == "Model2" ~ 1 + 1.2*x + rnorm(n(), 0, 1.2),
    model == "Model3" ~ 3 + 0.5*x + rnorm(n(), 0, 0.8)
  ))

# 新样本数据:4个待评估样本
new_data <- tibble(x = c(3, 5, 7, 9),
                   y = c(5, 8, 6, 10),
                   type = "New Sample")

方法一:扩展原有刻度,包含新样本

将新样本的类别加入训练模型的颜色/形状刻度中,统一管理图例:

ggplot(train_data, aes(x = x, y = y, color = model)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = TRUE) +
  # 添加新样本,同时映射颜色和形状
  geom_point(data = new_data, aes(x = x, y = y, color = type, shape = type), size = 3) +
  # 手动指定所有类别的颜色值
  scale_color_manual(values = c("Model1" = "#F8766D", "Model2" = "#00BA38", "Model3" = "#619CFF", "New Sample" = "#C77CFF")) +
  # 手动指定形状:训练样本用圆形,新样本用三角形
  scale_shape_manual(values = c("Model1" = 16, "Model2" = 16, "Model3" = 16, "New Sample" = 17)) +
  theme_minimal()

新样本的图例会与训练模型的图例合并,清晰区分两类数据。

方法二:用ggnewscale开启独立刻度

为新样本单独创建一套视觉属性刻度,避免与训练模型冲突:

library(ggnewscale)

ggplot(train_data, aes(x = x, y = y, color = model)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = TRUE) +
  # 开启新的颜色刻度,与之前的模型颜色刻度独立
  new_scale_color() +
  # 添加新样本,映射颜色到type
  geom_point(data = new_data, aes(x = x, y = y, color = type), size = 3, shape = 17) +
  # 指定新样本的颜色值,并修改图例标题
  scale_color_manual(values = c("New Sample" = "#C77CFF"), name = "待评估样本") +
  theme_minimal()

此方法会生成两个独立图例:一个对应训练模型,一个对应新样本,无多余图例。

注意事项

  • 使用ggnewscale时,new_scale_*()要放在新图层之前,确保新图层使用新刻度。
  • 若仅用形状区分新样本,可改用new_scale_shape(),逻辑相同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:22:06