How to Arrange an Arbitrary Number of Ggplots Using Grid.Arrange

How can I arrange an arbitrary number of ggplots using grid.arrange?

You're ALMOST there! The problem is that do.call expects your args to be in a named list object. You've put them in the list, but as character strings, not named list items.

I think this should work:

args.list <- c(plot.list, 2,2)
names(args.list) <- c("x", "y", "z", "nrow", "ncol")

as Ben and Joshua pointed out in the comments, I could have assigned names when I created the list:

args.list <- c(plot.list,list(nrow=2,ncol=2))

or

args.list <- list(x=x, y=y, z=x, nrow=2, ncol=2)

Grid Arrange mutliple ggplots from evaluated text

Making use of lapply this could be achieved like so:

Note: To make geom_histogram and geom_dotplot work I made y = wt a local aes for both the geom_point and geom_smooth as otherwise your code resulted in an error.

library(ggplot2)
library(gridExtra)
p <- ggplot(data = mtcars, aes(x = mpg, color = cyl))

p1 <- p + geom_point(aes(y = wt))
p2 <- p + geom_histogram()
p3 <- p + geom_dotplot()
p4 <- p + geom_smooth(aes(y = wt), method='lm')

tx <- paste0("p", 1:4)

grid.arrange(grobs = lapply(tx, function(x) eval(parse(text = x))), nrow = 2)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
#> `geom_smooth()` using formula 'y ~ x'

Sample Image

Arrange multiple ggplots using grid.arrange with labels and common.legend

You can use arrangeGrob from gridExtra to draw the final plot.

ggarrange(P1, P2, P3, labels = c("A", "B", "C"),  
ncol=3, nrow=1, common.legend = TRUE, legend="bottom")
grid.draw(arrangeGrob(P3,layout_matrix = matrix(c(3, 2, 1), nrow = 1)))

Sample Image

How do I arrange a variable list of plots using grid.arrange?

How about this:

library(gridExtra)
n <- length(plist)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(plist, ncol=nCol))

Sample Image

R: arranging multiple plots together using gridExtra

If you want to keep the approach you are using just add

par(mfrow=c(2,2))

before all four plots.

If you want everything on the same line add instead

par(mfrow=c(1,4))

Side-By-Side ggplots within rMarkdown using grid.arrange()

You can control the dimensions of the plots produced in an HTML report by including fig.width and fig.height in the beginning of the code chunk. Try to include {r, fig.width=12, fig.height=4} and see if the plots looks less squashed.



Related Topics



Leave a reply



Submit