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.

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)

plot of chunk unnamed-chunk-2

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.

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

plot of chunk unnamed-chunk-3

Decorating Plots

Because autoplot returns ggplot instance, you can decorate it as you want. To make autoplot API simple, ggfortify offers some options which must be done during ggplot instance creation. Additional decoration should be done after autoplot.

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

plot of chunk unnamed-chunk-4

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

plot of chunk unnamed-chunk-4

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

plot of chunk unnamed-chunk-5

# change colour mapping
p + scale_colour_brewer()

plot of chunk unnamed-chunk-5

Want Different Plots?

Internally, autoplot calls a generic function named ggplot2::fortify to convert the input to data.frame. As ggfortify defines fortify function for all the supported classes, you can use fortify to convert the instance to plot-friendly data.frame.

If you want a different type of plot, you can use fortify to get data.frame, then call ggplot in a normal way.

Following example shows a bar plot counting k-means clusters.

df <- fortify(kmeans(iris[-5], 3), data = iris)
head(df)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species cluster
## 1          5.1         3.5          1.4         0.2  setosa       2
## 2          4.9         3.0          1.4         0.2  setosa       2
## 3          4.7         3.2          1.3         0.2  setosa       2
## 4          4.6         3.1          1.5         0.2  setosa       2
## 5          5.0         3.6          1.4         0.2  setosa       2
## 6          5.4         3.9          1.7         0.4  setosa       2
ggplot(df, aes(x= cluster, fill = cluster)) + geom_bar()

plot of chunk unnamed-chunk-6