This document explains subplots related functions ggfortify. To use the functionality, you need to install the development version 0.0.4.9100 or later.
library(devtools)
install_github('sinhrks/ggfortify')
library(ggfortify)
packageVersion('ggfortify')
## [1] '0.0.4.9100'
autoplot may outputs subplots for some classes. For exmple, autoplot.lm draws diagnostics plots as below.
res <- lm(Volume ~ Girth, data = trees)
mp <- autoplot(res, ncol = 4)
mp
Because {ggplot2} itself cannot handle different kinds of plots in a single instance, {ggfortify} handle them using its original class named ggmultiplot. You can use + operator to decorate ggmultiplot.
class(mp)
## [1] "ggmultiplot"
## attr(,"package")
## [1] "ggfortify"
mp + theme_bw()
Also, + operator appends plots if ggplot or ggmultiplot instance is given as right-hand-side. Following example attaches 2 scatter plots after diagnostics.
mp +
(ggplot(trees, aes(Girth, Volume)) + geom_point()) +
(ggplot(trees, aes(Girth, Height)) + geom_point())
You can extract subset using [ and [[ operators.
mp[2:3]
mp[[1]]
You can extract arbitrary subset, modify, and draw.
mp[2:3] <- mp[2:3] + theme_bw()
mp
Assuming you want to plot multiple instances at once. ggfortify can accept list of supported instances and can output subplots.
Following example shows 3 kmeans plots changing number of clusters.
library(purrr)
res <- purrr::map(c(3, 4, 5), ~ kmeans(iris[-5], .))
autoplot(res, data = iris[-5], ncol = 3)
Next example shows multiple survival curves as subplots.
library(survival)
res <- list(a = survfit(Surv(time, status) ~ 1, data = lung),
b = survfit(Surv(time, status) ~ sex, data = lung))
autoplot(res)
You can pass a list contains different classes to autoplot.
library(vars)
data(Canada)
res <- list(a = Canada, b = AirPassengers)
autoplot(res)
You can instanciate ggmultiplot from a list of ggplot instances.
p1 <- ggplot(iris, aes(Petal.Width, Petal.Length)) + geom_point()
p2 <- ggplot(iris, aes(Petal.Width, Petal.Length)) + geom_point()
new('ggmultiplot', plots = list(p1, p2))
Layout can be specified via nrow and ncol keywords.
new('ggmultiplot', plots = list(p1, p2), ncol = 1)