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

ggplot2中不同数据集绘制相同变量时如何添加图例

ggplot2 多数据集同一变量的图例配置方法
  • 核心逻辑:ggplot2 的图例只能通过aes()中的美学映射自动生成,你之前将colour写在aes()外作为固定参数,不会触发图例生成逻辑。只需将颜色映射到对应分组的标识名称,即可自动生成图例。
  • 方法1:合并数据集(规范写法,更推荐)
    将多个数据集合并后新增分组列标记来源,一次完成映射,后续修改维护更方便。
library(ggplot2)
library(dplyr)

# 原有数据构造逻辑不变
A <- c(2001, 2002, 2003, 2004, 2005)
B <- c(3, 5, 2, 7, 5)
C <- c(2, 7, 4, 3, 5)

df1 <- data.frame(A, B)
df2 <- data.frame(A, C)
colnames(df1) <- c("Year","Value")
colnames(df2) <- c("Year","Value")

# 合并数据集并新增分组列
df_all <- bind_rows("df1" = df1, "df2" = df2, .id = "dataset")

test <- ggplot(df_all, aes(x = Value, y = Year, colour = dataset)) + 
  geom_path(size = 1) + 
  ylab("Year") + 
  scale_x_continuous(position = "top") + 
  scale_y_reverse(expand = c(0, 0)) +
  # 手动匹配分组与对应颜色
  scale_colour_manual(values = c("df1" = "red", "df2" = "blue"))
test
  • 方法2:不合并数据集,单独映射每个图层
    适合临时快速绘图的场景,分别在每个geom_path的aes()中指定颜色对应的分组名称即可。
library(ggplot2)

# 原有数据构造逻辑不变
A <- c(2001, 2002, 2003, 2004, 2005)
B <- c(3, 5, 2, 7, 5)
C <- c(2, 7, 4, 3, 5)

df1 <- data.frame(A, B)
df2 <- data.frame(A, C)
colnames(df1) <- c("Year","Value")
colnames(df2) <- c("Year","Value")

test <- ggplot() + 
  geom_path(data = df1, aes(x = Value, y = Year, colour = "df1"), size = 1) + 
  geom_path(data = df2, aes(x = Value, y = Year, colour = "df2"), size = 1) + 
  ylab("Year") + 
  scale_x_continuous(position = "top") + 
  scale_y_reverse(expand = c(0, 0)) +
  scale_colour_manual(
    name = "数据集来源", # 可自定义图例标题
    values = c("df1" = "red", "df2" = "blue")
  )
test

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:57:02