Monday, June 4, 2018

r - Plotting two variables as lines using ggplot2 on the same graph




A very newbish question, but say I have data like this:



test_data <-
data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
)



How can I plot both time series var0 and var1 on the same graph, with date on the x-axis, using ggplot2? Bonus points if you make var0 and var1 different colours, and can include a legend!



I'm sure this is very simple, but I can't find any examples out there.


Answer



For a small number of variables, you can build the plot manually yourself:



ggplot(test_data, aes(date)) + 
geom_line(aes(y = var0, colour = "var0")) +
geom_line(aes(y = var1, colour = "var1"))


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...