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

基于R语言ggplot的多产品独立时间序列折线图实现方案

没问题!我来帮你用R的ggplot搞定这个需求~你的数据目前是宽格式(每个月份单独一列),而ggplot更适合处理长格式数据,所以咱们先做数据转换,再生成每个产品的独立时间序列图,步骤很清晰:

步骤1:加载你的数据

先把你提供的数据还原到R环境里,这段代码直接复制就能用:

# 还原你给出的数据结构
df <- structure(list(Products = c("Prod_A", "Prod_B", "Prod_C"), 
                     `Jan-20` = c(15L, 1043L, 9L), 
                     `Feb-20` = c(20L, 1033L, 1L), 
                     `Mar-20` = c(18L, 1890L, 0L)), 
                class = "data.frame", row.names = c(NA, -3L))
步骤2:把宽格式转成ggplot友好的长格式

我们需要用tidyr包的pivot_longer函数,把分散的月份列合并成「月份」和「数值」两列,同时把月份字符串转成日期类型(这样时间轴才能正确排序):

# 先加载tidyverse包(包含ggplot2和tidyr)
library(tidyverse)

df_long <- df %>%
  # 把除了Products之外的列转成长格式
  pivot_longer(cols = -Products, 
               names_to = "Month", 
               values_to = "Value") %>%
  # 将"Jan-20"这类字符串转换成日期对象,方便排序
  mutate(Month = lubridate::my(Month))

这里用到的lubridate::my()函数专门处理「月份-年份」格式的字符串,非常省心~

步骤3:生成每个产品的独立时间序列图

用facet_wrap就能一键生成所有产品的独立图表,还能保持样式统一:

ggplot(df_long, aes(x = Month, y = Value, group = Products)) +
  # 绘制折线,设置颜色和粗细
  geom_line(color = "#2c3e50", linewidth = 1) +
  # 添加数据点,让趋势更清晰
  geom_point(color = "#e74c3c", size = 2) +
  # 按产品分面,ncol=1表示单列排列,你也可以改成2/3列
  facet_wrap(~Products, ncol = 1) +
  # 设置图表标题和坐标轴标签
  labs(title = "Monthly Sales Trend by Product",
       x = "Month",
       y = "Sales Volume") +
  # 用清爽的极简主题
  theme_minimal() +
  # 优化标题和X轴标签的样式,避免重叠
  theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
        axis.text.x = element_text(angle = 45, hjust = 1))

如果你的产品数值差异很大(比如Prod_B的数值远高于其他产品),可以给facet_wrap加个参数scales = "free_y",让每个图表的Y轴范围自适应,这样小数值产品的趋势也能看得清楚。

额外需求:批量保存单独的图表文件

如果你想把每个产品的图单独存成文件(比如PNG),可以用purrr包批量处理:

# 按产品拆分数据
product_groups <- df_long %>% group_split(Products)

# 循环每个产品,生成并保存图表
walk(product_groups, function(group) {
  # 获取当前产品名称
  prod_name <- unique(group$Products)
  # 生成该产品的图表
  plot <- ggplot(group, aes(x = Month, y = Value)) +
    geom_line(color = "#2c3e50", linewidth = 1) +
    geom_point(color = "#e74c3c", size = 2) +
    labs(title = paste("Monthly Trend for", prod_name),
         x = "Month",
         y = "Sales Volume") +
    theme_minimal() +
    theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))
  
  # 保存图表到当前工作目录
  ggsave(filename = paste0(prod_name, "_trend.png"), 
         plot = plot, 
         width = 6, 
         height = 4)
})

运行这段代码后,每个产品的图表会单独保存为Prod_A_trend.png、Prod_B_trend.png这样的文件,方便单独查看或分享。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:32:27