Skip to content

Instantly share code, notes, and snippets.

@stephaniehicks
Last active August 29, 2015 14:26
Show Gist options
  • Save stephaniehicks/d9bc6298dcbca4d0d892 to your computer and use it in GitHub Desktop.
Save stephaniehicks/d9bc6298dcbca4d0d892 to your computer and use it in GitHub Desktop.
arrange ggplot2 plots in a grid using cowplot
library(cowplot)
library(ggplot2)
library(PASWR)
data(Cows) # already in a "tidy" format
box.cow <- ggplot(Cows, aes(x = breed, y = butterfat, fill = age)) +
geom_boxplot() + labs(title = "Default cowplot theme")
save_plot("boxCow.jpeg", box.cow)
box.classic <- ggplot(Cows, aes(x = breed, y = butterfat, fill = age)) +
geom_boxplot() + theme_classic() + labs(title = "ggplot2 classic theme ")
save_plot("boxClassic.jpeg", box.classic)
box.gray <- ggplot(Cows, aes(x = breed, y = butterfat, fill = age)) +
geom_boxplot() + theme_gray() + labs(title = "Default ggplot2 theme")
save_plot("boxGray.jpeg", box.gray)
dens.cow <- ggplot(Cows, aes(x = butterfat, ..density.. )) +
geom_density(aes(colour = age), size = 1) + facet_grid(~breed)
save_plot("densCow.jpeg", dens.cow)
box.gray.grid <- ggplot(Cows, aes(x = breed, y = butterfat, fill = age)) +
geom_boxplot() + background_grid() + labs(title = "With a background grid")
save_plot("boxGrayGrid.jpeg", box.gray.grid)
fig1 <- plot_grid(box.cow, box.gray, box.gray.grid, dens.cow, ncol = 2,
align = "h", labels = c("A", "B", "C", "D"), label_size = 25)
save_plot("figure1.jpeg", fig1, ncol = 2, nrow = 2)
fig2 <- ggdraw() +
draw_plot(box.cow, x = 0, y = .5, width = .5, height = .5) +
draw_plot(box.gray, x = .5, y = .5, width = .5, height = .5) +
draw_plot(dens.cow, x = 0, y = 0, width = 1, height = .5) +
draw_plot_label(label = c("A", "B", "C"), size = 25,
x = c(0, 0.5, 0), y = c(1, 1, 0.5))
save_plot("figure2.jpeg", fig2, ncol = 2, nrow = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment