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.
First, install ggfortify from CRAN.
install.packages('ggfortify')
library(ggfortify)
ggplot2::autoplotThis 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')
Because autoplot returns ggplot instance, you can decorate it either way.
+ operator after calling autoplot.ggplot2::qplot. xlim, ylim, log, main, xlab, ylab and asp.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
# change colour mapping
p + scale_colour_brewer()
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.
NOTE In v0.0.1, fortify functions returns dplyr::tbl_df. As of v0.0.2, fortify returns normal data.frame because dplyr v0.4.0 or later no longer preserves rownames which may be required for plotting.
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()