The main package we need is ggplot2
, but we need another package which is one of its many extensions developed by the community: ggfortify
. This package depends on the zoo
package for time series and it helps to install that one as well.
# install.packages("ggplot2")
# install.packages("ggfortify")
# install.packages("zoo")
library(ggplot2)
library(ggfortify)
On a side note, the install.packages()
function handles dependencies with the dependencies =
argument, but I’m not sure how this works on a Mac (it should be the same). So, if you do not want to install a package and all its dependencies manually (like we just installed ggfortify
and zoo
), you can just run: install.packages("ggfortify", dependencies = TRUE)
and you should be good to go.
The single function in the ggfortify
package, which is of interest to us is the autoplot()
function, which is helpful to plot time series objects (i.e a ts
object) the ggplot way. Here is our first example with a simulated data set.
Interesting arguments: columns, facets, nrow, ncol, ts.geom, ts.colour, ts.size
# Construct a data frame of time series
ds <- as.data.frame(replicate(6, rnorm(100)))
ds <- ts(ds, start = 1990, frequency = 4)
colnames(ds) <- paste0("Variable", sep = "_", 1:ncol(ds))
# Plot the time series
autoplot(ds)
The autoplot()
function is extremely flexible and has many arguments to allow you to edit your plot exactly the way you want. Moreover, you can use all the power of the ggplot framework with the function. Let’s look at a few arguments you may like:
autoplot(ds, nrow = 3, ncol = 2)
autoplot(ds, columns = c("Variable_1", "Variable_3", "Variable_5"))
TRUE
): determines whether the series are plotted separately or in the same coordinates systemThe nice feature of this argument is that it assigns a different color to each series and automatically creates a legend in the plot.
autoplot(ds, c("Variable_1", "Variable_3"), facets = FALSE)
"bar"
, "ribbon"
, "point"
and others.autoplot(ds, nrow = 3, ncol = 2, geom = "bar")
autoplot(ds, nrow = 3, ncol = 2, geom = "ribbon")
autoplot(ds, nrow = 3, ncol = 2, geom = "point")
There are many other arguments to the function: colour, size, linetype, alpha, fill, shape, xlim, ylim, xlab, ylab, main …
I would like to end this with the scale
argument. It takes one of three arguments "free_x"
, "free_y"
or "free"
. The purpose of the argument is to make the horizontal and vertical axes for each plot independent of other plots.
autoplot(ds, nrow = 3, ncol = 2, scale = "free")
There is no limit on the number of variables that autoplot()
can display. Afterall, it is a function in the ggplot2
framework.