Niko Gamulin - 6 months ago 123

R Question

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

For example, having two datasets:

dataset1(Date, value)

and

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)

plot(x)

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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

objects.

```
set.seed(1)
xz = zoo(ts(rnorm(20), frequency = 4, start = c(1959, 2)))
yz = zoo(ts(rnorm(20), frequency = 4, start = c(1959, 2)))
# Basic approach
plot(xz)
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`

:

```
set.seed(1)
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")))
```