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

如何将行式时间序列数据转换为long格式以绘制多折线图?

将宽格式数据转换为长格式以绘制ggplot折线图

原始数据结构

Trial        1        2        3        4        5        6        7        8        9
1    x1 69824.35 67628.96 67976.71 68263.39 68500.94 68698.74 68864.20 69003.20 69120.43
2    x2 69824.35 67628.96 67991.52 68290.91 68538.68 68744.19 68915.02 69057.35 69176.19
3    x3 69824.35 67628.96 67973.59 68258.04 68494.10 68691.00 68856.02 68994.91 69112.27
4    x4 69824.35 67628.96 67939.18 68205.13 68433.12 68628.56 68796.14 68939.84 69063.11
5    x5 69824.35 67628.96 67983.88 68278.10 68522.57 68726.19 68896.15 69038.34 69157.55
6    x6 69824.35 67628.96 67955.75 68231.44 68464.40 68661.55 68828.66 68970.55 69091.22

注:每行对应一个分组(x1-x6),列1到9对应不同Trial的数值,我们需要将其转换为长格式——每个分组+每个Trial对应一行记录(推测你给出的示例中Trial列值是笔误,应为1到9依次排列)。


两种转换方法

方法1:使用tidyr的pivot_longer(推荐,tidyverse生态)

这是当前处理宽转长最常用的工具,和ggplot无缝兼容。

假设你读取数据后的数据框名为df,列结构为:第一列是行号(可忽略),第二列是分组(x1-x6),第三到第十一列是Trial 1到9的数值(列名为1到9)。执行以下代码:

# 先安装/加载tidyr包
# install.packages("tidyr")
library(tidyr)

# 转换为长格式:排除前两列(行号和分组),将剩余列转为Trial和Value列
long_df <- pivot_longer(df,
                        cols = -c(1, 2),  # 若知道列名,也可写为 -c(row_id, group)
                        names_to = "Trial",
                        values_to = "Value")

转换后的数据结构(以x1为例):

row_id group Trial   Value
1      x1    1      69824.35
1      x1    2      67628.96
1      x1    3      67976.71
...    ...   ...    ...

方法2:使用reshape2的melt(你熟悉的工具)

如果你习惯用reshape系列的melt函数,用reshape2包同样可以实现:

# 安装/加载reshape2包
# install.packages("reshape2")
library(reshape2)

# 转换长格式:指定保留的标识列,以及新列的名称
long_df <- melt(df,
                id.vars = c(1, 2),  # 保留行号和分组列
                variable.name = "Trial",
                value.name = "Value")

绘制折线图

转换完成后,直接用ggplot绘制多条折线:

library(ggplot2)
ggplot(long_df, aes(x = as.numeric(Trial), y = Value, color = group)) +
  geom_line(linewidth = 1) +
  labs(x = "Trial", y = "数值", color = "分组")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:09:59