This document explains time series related plotting using ggplot2 and ggfortify.
First, install ggfortify from github.
library(devtools)
install_github('sinhrks/ggfortify')
ggfortify let ggplot2 know how to interpret ts objects. After loading ggfortify, you can use ggplot2::autoplot function for ts objects.
library(ggfortify)
autoplot(AirPassengers)
To change line colour and line type, use ts.colour and ts.linetype options. Use help(autoplot.ts) (or help(autoplot.*) for any other objects) to check available options.
autoplot(AirPassengers, ts.colour = 'red', ts.linetype = 'dashed')
Multivariate time series will be drawn with facets.
library(vars)
data(Canada)
autoplot(Canada)
Specify facets = FALSE to draw on single axes.
autoplot(Canada, facets = FALSE)
Also, autoplot can handle other time-series-likes. Supported packages are:
zoo::zooregxts::xtstimeSeries::timSeriestseries::irtslibrary(xts)
autoplot(as.xts(AirPassengers), ts.colour = 'green')
library(timeSeries)
autoplot(as.timeSeries(AirPassengers), ts.colour = ('dodgerblue3'))
You can change {ggplot2} geometrics specifying by its name. Geometrics currently supported are line, bar and point.
autoplot(AirPassengers, ts.geom = 'bar', fill = 'blue')
autoplot(AirPassengers, ts.geom = 'point', shape = 3)
ggfortify supports forecast object in forecast package.
library(forecast)
d.arima <- auto.arima(AirPassengers)
d.forecast <- forecast(d.arima, level = c(95), h = 50)
autoplot(d.forecast)
There are some options to change basic settings.
autoplot(d.forecast, ts.colour = 'firebrick1', predict.colour = 'red',
predict.linetype = 'dashed', conf.int = FALSE)
ggfortify supports varpred object in vars package.
library(vars)
d.vselect <- VARselect(Canada, lag.max = 5, type = 'const')$selection[1]
d.var <- VAR(Canada, p = d.vselect, type = 'const')
Available options are the same as forecast.
autoplot(predict(d.var, n.ahead = 50), ts.colour = 'dodgerblue4',
predict.colour = 'blue', predict.linetype = 'dashed')
ggfortify supports cpt object in changepoint package.
library(changepoint)
autoplot(cpt.meanvar(AirPassengers))
You can change some options for cpt.
autoplot(cpt.meanvar(AirPassengers), cpt.colour = 'blue', cpt.linetype = 'solid')
ggfortify supports breakpoints object in strucchange package. Same plotting options as changepoint are available.
library(strucchange)
autoplot(breakpoints(Nile ~ 1), ts.colour = 'blue', ts.linetype = 'dashed',
cpt.colour = 'dodgerblue3', cpt.linetype = 'solid')