Last active
July 6, 2016 04:48
-
-
Save darthsuogles/c6275b7d0b11b54114261ea97fcb885f to your computer and use it in GitHub Desktop.
Multiple histograms in a grid, each with its own y-axis scale
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(ggplot2) | |
| # First get the Iris histogram | |
| histo_list <- lapply(names(iris)[1:4], | |
| function (colname) qplot(iris[[colname]], geom = "histogram", xlab = colname)) | |
| # Add two sets of random normal samples | |
| n <- 100 | |
| histo_list[[5]] <- qplot(rnorm(n), geom='histogram', xlab='rand-norm-1') | |
| histo_list[[6]] <- qplot(rnorm(n), geom='histogram', xlab='rand-norm-2') | |
| multiplot <- function(..., plotlist=NULL, file, cols=1, title=NULL, layout=NULL) { | |
| library(grid) | |
| ## Make a list from the ... arguments and plotlist | |
| plots <- c(list(...), plotlist) | |
| numPlots = length(plots) | |
| ## If layout is NULL, then use 'cols' to determine layout | |
| if (is.null(layout)) { | |
| ## Make the panel | |
| ## ncol: Number of columns of plots | |
| ## nrow: Number of rows needed, calculated from # of cols | |
| layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), | |
| ncol = cols, nrow = ceiling(numPlots/cols)) | |
| } | |
| if (numPlots==1) { | |
| print(plots[[1]]) | |
| } else { | |
| ## Set up the page | |
| grid.newpage() | |
| pos_shift <- 0 | |
| if ( is.null(title) ) { | |
| pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout)))) | |
| } else { | |
| pushViewport(viewport( | |
| layout = grid.layout(1 + nrow(layout), ncol(layout), | |
| heights = unit(c(1, rep(4, nrow(layout))), 'null')))) | |
| grid.text(title, vp = viewport(layout.pos.row = 1, layout.pos.col = 1:ncol(layout))) | |
| pos_shift <- 1 | |
| } | |
| ## Make each plot, in the correct location | |
| for (i in 1:numPlots) { | |
| ## Get the i,j matrix positions of the regions that contain this subplot | |
| matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE)) | |
| print(plots[[i]], vp = viewport(layout.pos.row = pos_shift + matchidx$row, | |
| layout.pos.col = matchidx$col)) | |
| } | |
| } | |
| } | |
| multiplot(plotlist = histo_list, cols = 2, title = "a grid plot") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment