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.
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.
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.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With