Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
fmark Avatar asked Sep 23 '10 09:09

fmark


People also ask

How do you plot multiple lines on a graph in R?

In this method to create a ggplot with multiple lines, the user needs to first install and import the reshape2 package in the R console and call the melt() function with the required parameters to format the given data to long data form and then use the ggplot() function to plot the ggplot of the formatted data.

How do you plot two series on the same graph in R?

To plot the two graphs in the same plot, we can use the par() function in R language. Similarly, you can also use the lines() or points() function to add the graph to an existing plot.


1 Answers

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")) 
like image 94
hadley Avatar answered Sep 24 '22 00:09

hadley