fmark fmark - 3 months ago 11
R Question

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 use build up the plot manually yourself:

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