This document explains concepts and basics of ggfortify. ggfortify helps plotting some popular R packages with ggplot2 in a unified way. See github to check the list of supported packages / classes.

Installation

First, install ggfortify from CRAN.

install.packages('ggfortify')

Loading Packages

library(ggfortify)

Using ggplot2::autoplot

This is the easiest way to use ggfortify. Calling autoplot with supported instance should output “natural” plot, as standard plot function does.

autoplot(AirPassengers)

You can specify some options to control plotting properties. As is often the case with statistic classes, there are some objects to be drawn, such as actual value, predicted value and confidence interval, etc. Thus, each plotting option has a format like <target name>.<ggplot option name> such as ts.colour and conf.int.linetype.

These options can be used for the similar type of instances commonly. For example, ts.colour works for all time-series-likes, rather than having separate options such as xts.colour and timeSeries.colour. To check available options, use help(autoplot.ts) or help(autoplot.*) for any other objects.

NOTE See the doc for supported time-series-like classes.

autoplot(AirPassengers, ts.colour = 'blue')

Decorating Plots

Because autoplot returns ggplot instance, you can decorate it either way.

p <- 

p <- autoplot(AirPassengers)
class(p)
## [1] "gg"     "ggplot"
# plot as it is
p

# add title and labels
p + ggtitle('AirPassengers') + xlab('Year') + ylab('Passengers')

# or specify them via options
autoplot(AirPassengers, main = 'AirPassengers', xlab = 'Year', ylab = 'Passengers')

set.seed(1)
p <- autoplot(kmeans(iris[-5], 3), data = iris)
# plot as it is
p