如何按时间序列绘制数据

时间:2017-05-04 01:49:48

标签: r plot

我的数据如下:

  time sucrose fructose glucose galactose molasses water
1    5     0.0     0.00     0.0       0.0      0.3     0
2   10     0.3     0.10     0.1       0.0      1.0     0
3   15     0.8     0.20     0.2       0.2      1.4     0
4   20     1.3     0.35     0.7       0.4      2.5     0
5   25     2.2     0.80     1.6       0.5      3.5     0
6   30     3.1     1.00     2.3       0.6      4.5     0
7   35     3.6     1.60     3.1       0.7      5.7     0
8   40     5.1     2.80     4.3       0.7      6.7     0

如何创建使用时间列的时间序列图?它们都在增加价值。

我看到这篇帖子multiple-time-series-in-one-plot使用ts.plot来实现类似于我想要展示的内容,这就是:

time-series plot

上表的输入数据:

structure(list(time = c(5, 10, 15, 20, 25, 30, 35, 40), sucrose = c(0, 
0.3, 0.8, 1.3, 2.2, 3.1, 3.6, 5.1), fructose = c(0, 0.1, 0.2, 
0.35, 0.8, 1, 1.6, 2.8), glucose = c(0, 0.1, 0.2, 0.7, 1.6, 2.3, 
3.1, 4.3), galactose = c(0, 0, 0.2, 0.4, 0.5, 0.6, 0.7, 0.7), 
    molasses = c(0.3, 1, 1.4, 2.5, 3.5, 4.5, 5.7, 6.7), water = c(0, 
    0, 0, 0, 0, 0, 0, 0)), .Names = c("time", "sucrose", "fructose", 
"glucose", "galactose", "molasses", "water"), row.names = c(NA, 
-8L), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

似乎不需要ts图。以下是你在base-R中的表现:

with(df, plot(time, sucrose, type="n", ylab="contents"))
var <- names(df)[-1]
for(i in var) lines(df$time, df[,i])

enter image description here

然而,更优雅的解决方案是使用'dplyr and ggplot2`包:

df <- df %>% 
      gather(content, val, -time)

ggplot(df, aes(time, val, col=content)) + geom_line()

enter image description here