Skip to content

Instantly share code, notes, and snippets.

@sithjaisong
Last active August 29, 2015 14:20
Show Gist options
  • Save sithjaisong/bf19965c592667976e1b to your computer and use it in GitHub Desktop.
Save sithjaisong/bf19965c592667976e1b to your computer and use it in GitHub Desktop.
loop for multiple ggplot and arrange them in the rows and columns you wish for
###########################Header##############################################
# title : multiggplot.R;
# purpose : create muti histogram of all varibles in the dataset;
# producer : prepared by S. Jaisong ([email protected]);
# last update : in Los Baños, Laguna, PHL, April 2015;
# inputs : "airquality" data from R;
# outputs : exaple.pdf;
# remarks 1 : ;
# remarks 2 : ;
###############################End#############################################
#==== Start loading the packages
library(reshape)
library(reshape2)
library(ggplot2)
library(gridExtra)
#===== End loading the packages =============
#==> what is your dataframe
dat <- airquality # what is your data frame that you want to plot the graphs
#========================================================================
varnames <- names(dat) # creat the list of variables of you data frame
m.dat <- melt(dat)
names(m.dat)
#============== loop for create multiple graphs of each variable in the data frame
i <- 1
out <- NULL # crerate the list for saving the output file from the ggplot
for(i in 1:length(varnames)) {
temp <- subset(m.dat, variable %in% varnames[i])
p <- ggplot(temp, aes(x = value)) +
geom_histogram(stat = "bin") + ggtitle(paste("Histogram of", varnames[i], sep = " "))
dev.new()
print(p)
out[[i]] <- p
}
pdf(file = "example.pdf", width = 20, height = 15) # define the name of outout graphs
g <- grid.arrange(out[[1]],
out[[2]],
out[[3]],
out[[4]],
nrow = 2 # layout graphs 2 rows
)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment