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

使用Ggplot2按年份设置X轴标签颜色并添加对应图例的方法

R语言绘制分年份彩色X轴标签的时序图

前置准备

使用提供的示例数据完成预处理:

# ggplot2方案依赖包,base R方案可跳过
library(ggplot2)
library(lubridate) 

# 示例数据
dates = seq.Date(from =as.Date("01/01/2020", "%d/%m/%Y"), 
                 to=as.Date("01/03/2021", "%d/%m/%Y"), by="month")
y = c(1:15)
df = data.frame(dates,y)

# 新增年份分组列用于生成图例,未装lubridate可替换为 df$year <- as.factor(format(df$dates, "%Y"))
df$year <- as.factor(year(df$dates))

方案1:ggplot2实现(推荐)

可同时满足自定义X轴标签颜色、自动生成匹配图例的需求:

# 生成X轴标签颜色向量:前12个2020年数据为蓝色,后3个2021年数据为绿色
x_label_colors <- c(rep("blue", 12), rep("green", 3))

ggplot(df, aes(x = dates, y = y)) +
  geom_line() +
  # 点的颜色按年份映射,用于生成对应图例
  geom_point(aes(color = year), size = 2) +
  # 设置X轴为日期格式,显示年-月标签
  scale_x_date(date_labels = "%Y-%m", breaks = df$dates) +
  # 自定义X轴标签颜色
  theme(
    axis.text.x = element_text(color = x_label_colors, angle = 45, hjust = 1)
  ) +
  # 自定义图例样式
  scale_color_manual(
    values = c("2020" = "blue", "2021" = "green"),
    name = "年份",
    labels = c("2020年", "2021年")
  ) +
  labs(x = "日期", y = "数值")

方案2:base R实现

# 绘制基础折线图,先隐藏默认X轴
plot(df$dates, df$y, type = "o", xaxt = "n", xlab = "日期", ylab = "数值")
# 计算标签位置,自定义X轴带颜色标签
x_label_pos <- par("usr")[1] - diff(par("usr")[1:2])*0.08
text(x = df$dates, y = x_label_pos, labels = format(df$dates, "%Y-%m"), 
     col = c(rep("blue",12), rep("green",3)), srt = 45, adj = 1, xpd = TRUE)
# 添加图例
legend("topleft", legend = c("2020年", "2021年"), 
       col = c("blue", "green"), pch = 1, lty = 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 21:42:02