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

R语言绘制数值变量时间序列图如何添加变量对应颜色图例

解决方案

你遇到的问题本质是没有把「变量类别」映射到ggplot的color美学属性上,而是直接单独指定了两条线的颜色,因此无法自动生成图例,以下是两种可行的实现方案:

方法1:将宽数据转为长格式(推荐做法)

当前你的数据集属于宽格式,每个指标单独占一列,先将指标列转为长格式,再映射到color属性即可自动生成图例:

library(tidyverse)

# 1. 数据格式转换
df_long <- df %>% 
  select(Year, `CrecimientoPBI (%)`, `Inflación (%)`) %>% 
  pivot_longer(
    cols = -Year,
    names_to = "指标类型",
    values_to = "数值"
  ) %>% 
  # 替换为你需要的图例标签
  mutate(指标类型 = case_when(
    指标类型 == "CrecimientoPBI (%)" ~ "PBI Growth",
    指标类型 == "Inflación (%)" ~ "Inflation"
  ))

# 2. 绘图
ggplot(df_long, aes(x = as.numeric(Year), y = 数值, color = 指标类型)) +
  geom_line(linewidth = 1) +
  # 手动设置颜色对应关系
  scale_color_manual(
    values = c("PBI Growth" = "red", "Inflation" = "blue"),
    name = "" # 可自定义图例标题,留空则不显示
  ) +
  labs(x = "年份", y = "占比(%)") +
  theme_minimal()

方法2:不转换数据,手动映射颜色标签

如果你不想修改原始数据结构,也可以在geom_line的美学映射里直接指定颜色对应的标签,再手动绑定颜色:

ggplot(df, aes(x = as.numeric(Year))) +
  geom_line(aes(y = `CrecimientoPBI (%)`, color = "PBI Growth"), linewidth = 1) +
  geom_line(aes(y = `Inflación (%)`, color = "Inflation"), linewidth = 1) +
  scale_color_manual(
    values = c("PBI Growth" = "red", "Inflation" = "blue"),
    name = ""
  ) +
  labs(x = "年份", y = "占比(%)") +
  theme_minimal()

之前使用aes(col = as.factor(...))未生效的原因是你将数值列本身转为了因子,会把每个数值都识别为一个独立分类,自然会生成大量无效的颜色分类,我们需要映射的是「变量所属的类别」而非变量的数值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:54:04