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.
One disadvantage for par() is that it cannot work for ggplot, we can see below that the plot should appear on the upper left of the page, but it just happen as if par() isn't written here.
ggplot only works with data frames, so we need to convert this matrix into data frame form, with one measurement in each row. We can convert to this “long” form with the melt function in the library reshape2 . Notice how ggplot is able to use either numerical or categorical (factor) data as x and y coordinates.
This should get you started:
install.packages("gridExtra")
library(gridExtra)
grid.arrange(plot1, plot2, ..., ncol=3, nrow = 3)
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With