Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

par(mfrow) in R for ggplot [duplicate]

Tags:

r

ggplot2

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.

like image 254
Ar De Avatar asked Apr 11 '17 21:04

Ar De


People also ask

Does par () work with 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.

Does Ggplot only work with data frames?

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.


2 Answers

This should get you started:

install.packages("gridExtra")
library(gridExtra)
grid.arrange(plot1, plot2, ..., ncol=3, nrow = 3)
like image 192
Julian Wittische Avatar answered Nov 15 '22 04:11

Julian Wittische


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 )
like image 23
Artem Sokolov Avatar answered Nov 15 '22 05:11

Artem Sokolov