Niko Gamulin Niko Gamulin - 6 months ago 123
R Question

How to plot overlaying time series in R?

I would like to compare the values of two different variables in time.

For example, having two datasets:

dataset1(Date, value)
dataset2(Date, value)

In order to plot just first, we can execute the following:

x.Date <- as.Date(dataset1$Date)
x <- zoo(dataset1$Value, x.Date)

To the same window I would like to add (dataset2$value, dataset2$Date), and by chance set the different color.

the values dataset1$Date and dataset2$Date are not neccessary the same (some days might overlap and some not), for example dataset1$Date might contain (dec01, dec02, dec03, dec05) and dataset2$Date (dec02, dec03, dec06).

Does anyone know how to plot two (or several) time plots in the same window?

Answer Source

There are several options. Here are three options working with zoo objects.

xz = zoo(ts(rnorm(20), frequency = 4, start = c(1959, 2)))
yz = zoo(ts(rnorm(20), frequency = 4, start = c(1959, 2)))
# Basic approach
lines(yz, col = "red")
# Panels
plot.zoo(cbind(xz, yz))
# Overplotted
plot.zoo(cbind(xz, yz), 
         plot.type = "single", 
         col = c("red", "blue"))

If you are plotting regular ts objects, you can also explore ts.plot:

x = ts(rnorm(20), frequency = 4, start = c(1959, 2))
y = ts(rnorm(20), frequency = 4, start = c(1959, 2))
ts.plot(x, y, gpars = list(col = c("black", "red")))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download