I would like to place two plots side by side using the ggplot2 package, i.e. do the equivalent of par(mfrow=c(1,2))
.
For example, I would like to have t
The above solutions may not be efficient if you want to plot multiple ggplot plots using a loop (e.g. as asked here: Creating multiple plots in ggplot with different Y-axis values using a loop), which is a desired step in analyzing the unknown (or large) data-sets (e.g., when you want to plot Counts of all variables in a data-set).
The code below shows how to do that using the mentioned above 'multiplot()', the source of which is here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2):
plotAllCounts <- function (dt){
plots <- list();
for(i in 1:ncol(dt)) {
strX = names(dt)[i]
print(sprintf("%i: strX = %s", i, strX))
plots[[i]] <- ggplot(dt) + xlab(strX) +
geom_point(aes_string(strX),stat="count")
}
columnsToPlot <- floor(sqrt(ncol(dt)))
multiplot(plotlist = plots, cols = columnsToPlot)
}
Now run the function - to get Counts for all variables printed using ggplot on one page
dt = ggplot2::diamonds
plotAllCounts(dt)
One things to note is that:
using aes(get(strX))
, which you would normally use in loops when working with ggplot
, in the above code instead of aes_string(strX)
will NOT draw the desired plots. Instead, it will plot the last plot many times. I have not figured out why - it may have to do the aes
and aes_string
are called in ggplot
.
Otherwise, hope you'll find the function useful.