9

I have this code:

plotfn= function(u) {
  flt = filter(d, utensil ==u)
  ggplot(flt,aes(x=p)) + geom_histogram(binwidth = 0.5, position= position_dodge(0.5), color="black",fill="cadetblue4")+ ggtitle("Histogram of P")+labs( x="P", y="Number of Observations")
}
lapply(unique(d$utensil),plotfn)

I tried doing a par(mfrow= c(3,3)) to get all 9 plots in 1 screen but it doesn't work. I have to use ggplot.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
Ar De
  • 105
  • 1
  • 1
  • 3
  • 1
    Useful: http://www.cookbook-r.com/Graphs/ (see the "Facets" chapter) – Stéphane Laurent Apr 11 '17 at 22:03
  • 1
    Also, this question may be of help: http://stackoverflow.com/questions/5226807/multiple-graphs-in-one-canvas-using-ggplot2 – Stedy Apr 11 '17 at 22:20
  • Why not use `facet_grid`? The Ggplot system is designed to avoid this sort of messing around. You might wan `grid.arrange` for two different types of plot but not for all 9 of the same type. – IRTFM Apr 11 '17 at 23:36

2 Answers2

10

This should get you started:

install.packages("gridExtra")
library(gridExtra)
grid.arrange(plot1, plot2, ..., ncol=3, nrow = 3)
Julian Wittische
  • 1,219
  • 14
  • 22
8

Take a look at the gridExtra package, which integrates nicely with ggplot2 and allows you to place multiple plots onto a single page: https://cran.r-project.org/web/packages/gridExtra/vignettes/arrangeGrob.html

To use it, store the output of your ggplot calls to a variable, then pass that variable to grid.arrange:

myGrobs <- lapply(unique(d$utensil),plotfn)
gridExtra::grid.arrange( grobs = myGrobs, nrow = 3 )
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74