【问题标题】:Multiple time series plots using ggplot2 with each having unequal number of observations使用 ggplot2 绘制多个时间序列图,每个时间序列图的观测数不相等
【发布时间】:2023-03-18 22:47:01
【问题描述】:

我正在根据以下描述寻求有关多个时间序列图的帮助。

我有一个具有以下结构的数据框。列 isin 是重复的,它有 5 个唯一值。对于每个 isin,都有多行数据,由 t_week、MS 和 t_MS 组成。每个 isin 的行数不相等。换句话说,数据框有 2 个时间序列 (t_week, MS) (t_week, t_MS),每个 isin 具有不相等的数据点数。

我想使用 ggplot2 在一个图上绘制所有 5 个 isin 时间序列(t_week,MS)。我可以轻松绘制多个等长的时间序列,但在这里寻求帮助以正确的“R”方式进行。请帮忙。

问候

K

str(df)
'data.frame':   95 obs. of  4 variables:
 $ isin  : chr  "IN0019960056" "IN0019960056" "IN0019960056" "IN0019960056" ...
 $ t_week: Date, format: "2006-01-09" "2006-01-16" ...
 $ MS    : num  0 0 0.01 0.86 0.54 0.23 1.55 0.07 0.29 0.79 ...
 $ t_MS  : num  0.14 0.14 0.14 0.75 0.35 0.31 0.63 0.28 0.54 0.52 ...

【问题讨论】:

标签: r ggplot2


【解决方案1】:

canocialggplot2方式如下:

ggplot(df, aes(x = t_week, y = MS, color = isin)) + geom_line()

这将构建t_weekMS 的图,isin 中的每个唯一元素都有不同颜色的线。时间序列不包含相同数量的行是没有问题的,它们甚至不必覆盖相同的时间范围。一个例子:

df_part1 = data.frame(t_week = seq(1,5,length=100), MS = runif(100), isin = "A")
df_part2 = data.frame(t_week = seq(2,6,length=500), MS = runif(500) + 1, isin = "B")
df = rbind(df_part1, df_part2)

library(ggplot2)
ggplot(df, aes(x = t_week, y = MS, color = isin)) + geom_line()

【讨论】:

  • 这太棒了@Paul。谢谢一堆。我正在尝试使用 ddply 和 melt 导致不明智的情节的各种组合。我没有想到 ISIN 可以被视为分类变量,而 ggplot 最终会成功。再次感谢出色的解决方案。
  • 如果这解决了您的问题,您可以通过单击我的答案旁边左侧的绿色对勾标记它。
猜你喜欢
  • 2018-07-05
  • 2021-05-12
  • 2017-05-09
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2019-05-04
  • 2019-12-02
  • 2017-03-04
相关资源
最近更新 更多