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

R ggplot2绘制跨年度冬季周度分赛季销售折线图

R ggplot冬季周度销售额折线图实现方案

核心需要先完成两项数据预处理,再执行绘图逻辑:

  • 生成独立的冬季赛季标识,替代原自然年字段作为折线分组、配色的依据,解决跨年度数据拆分错误的问题
  • 手动指定周编号的因子水平顺序,强制x轴按50→51→52→1→2→3→4的冬季周序排列,解决x轴排序错误的问题

完整可运行代码

library(ggplot2)
library(dplyr) # 未安装可先运行 install.packages("dplyr")

# 原示例数据
df <- data.frame(
  week_no = c("50","51","52","1","2","3","4","50","51","52","1","2","3","4"),
  date = c("2018-12-14", "2018-12-21", "2018-12-28", "2019-01-04", "2019-01-11", "2019-01-18", "2019-01-25", "2019-12-13", "2019-12-20", "2019-12-27", "2020-01-03", "2020-01-10", "2020-01-17", "2020-01-24"), 
  year = c("2018", "2018", "2018", "2019", "2019", "2019", "2019", "2019", "2019", "2019", "2020", "2020", "2020", "2020"),
  sales = c(546,873,532,424,235,321,531,865,869,458,234,654,345,984)
)

# 数据预处理
df_processed <- df %>%
  mutate(
    week_num = as.numeric(week_no),
    # 按规则生成跨年度冬季赛季标签
    winter_season = case_when(
      week_num >= 50 ~ paste0(year, "-", as.numeric(year)+1, "冬季赛季"),
      week_num <=4 ~ paste0(as.numeric(year)-1, "-", year, "冬季赛季")
    ),
    # 固定周编号的x轴排列顺序
    week_no = factor(week_no, levels = c("50","51","52","1","2","3","4"))
  )

# 绘图
winter_line_plot <- ggplot(df_processed, aes(x = week_no, y = sales, group = winter_season)) + 
  geom_line(aes(color = winter_season), linewidth = 1) +
  geom_point(aes(color = winter_season)) + # 可选,添加数据点提升可读性
  labs(x = "周编号(冬季时段)", y = "销售额", color = "冬季赛季") +
  theme_bw()

# 输出图表
print(winter_line_plot)

关键逻辑说明

  • 原代码直接用自然年year做分组维度,会把同一冬季里归属于不同自然年的周数据拆分为独立组,导致折线断裂、年份匹配错误。自定义winter_season字段后,跨自然年的同一冬季时段会被归为同一分组,每条折线对应一个完整冬季赛季
  • ggplot默认对字符型x轴按数值/字典序排列,将week_no转为手动指定水平的因子后,会严格按照设定的冬季周序展示,不会出现周数1排在50前面的问题
  • aes中显式声明group = winter_season,可明确分组规则,避免不同赛季的数据被误连为同一条折线

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:36:10