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

如何在R的ggplot折线图中按月份区间设置分段颜色并添加图例

按月份分段设置折线图颜色并添加图例(R语言ggplot2实现)

实现步骤:

  1. 添加月份分组列:根据月份范围将12个月划分为4个颜色组,匹配你要求的颜色规则。
  2. 构建线段数据:将每个月份的数据点与下一个月份的点配对,用于绘制分段颜色的折线。
  3. 使用geom_segment绘制分段折线:替代原geom_line,通过线段连接相邻点,并按分组设置颜色。
  4. 自定义颜色与图例:手动指定每组对应的颜色,确保图例正确显示。

修改后的完整代码:

library(ggplot2)
library(dplyr)

# 原始数据
temperature <- data.frame(
  stringsAsFactors = FALSE,
  Year= c(1998,1998,1998,1998,1998,1998,1998,1998,1998,1998,1998,1998,1999,1999,1999,1999,1999,1999,1999,1999,1999,1999,1999,1999,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2001,2001,2001,2001,2001,2001,2001,2001,2001,2001,2001,2001,2002,2002,2002,2002,2002,2002,2002,2002,2002,2002,2002,2002),
  Month = c(1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12),
  Temperature = c(5,6,7,12,15,16,27,28,22,10,11,6,6,6,7,13,16,15,25,26,24,12,11,4,5,6,7,12,15,17,28,30,22,10,11,7,7,7,7,12,18,17,25,24,20,3,3,4,5,6,7,12,15,16,27,28,22,10,11,6),
  check.names = FALSE
)

# 转换日期格式
temperature$date = as.Date(paste(temperature$Year, temperature$Month,1), format = "%Y %m %d")

# 1. 添加月份分组列,对应颜色规则
temperature$season_group <- cut(temperature$Month,
                                breaks = c(0, 3, 6, 9, 12),
                                labels = c("1-3月", "4-6月", "7-9月", "10-12月"),
                                include.lowest = TRUE)

# 2. 构建线段数据:每个点连接到下一个点
temp_segments <- temperature %>%
  mutate(next_date = lead(date),
         next_temp = lead(Temperature)) %>%
  filter(!is.na(next_date))

# 3. 绘制分段颜色折线图
ggplot(temp_segments,
       aes(x = date, xend = next_date,
           y = Temperature, yend = next_temp,
           color = season_group)) +
  geom_segment(linewidth = 1) +  # 绘制分段线段
  ggtitle("气温时间序列(按月份分段着色)") +
  scale_x_date(date_breaks = "year", date_labels = "%Y", date_minor_breaks = "month") +
  # 4. 手动指定每组颜色,并设置图例名称
  scale_color_manual(name = "月份区间",
                     values = c("1-3月" = "yellow",
                                "4-6月" = "red",
                                "7-9月" = "green",
                                "10-12月" = "blue")) +
  xlab("年份") +
  ylab("气温") +
  theme_minimal()

代码说明:

  • cut()函数将月份划分为4个区间,生成season_group列作为颜色映射的依据。
  • lead()函数获取下一个月份的日期和气温数据,用于构建线段的终点。
  • geom_segment()替代geom_line,实现按分组给每个线段上色,完美匹配你要求的月份颜色规则。
  • scale_color_manual()自定义颜色与图例,让图例清晰展示每个颜色对应的月份区间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:27:34