Daniel Quomsieh
Daniel Quomsieh

Reputation: 25

how to plot data in time series

I have data that looks like this:

  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

How can i make a time series plot that uses the time column? They are all increasing values.

I saw this post multiple-time-series-in-one-plot which uses ts.plot to achieve something similar to what i want to show, which is this:

time-series plot

Input data for the table above:

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")

Upvotes: 0

Views: 165

Answers (1)

Adam Quek
Adam Quek

Reputation: 7163

It doesn't seem like a ts plot is necessary. Here's how you could do it in 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

The more elegant solution would however be using the 'dplyrandggplot2` package:

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

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

enter image description here

Upvotes: 1

Related Questions