iatowks
iatowks

Reputation: 1040

How to use with plot_grid from cowplot

I want to combine several ggplot2 charts into one using cowplot::plot_grid(). From its documentation:

?plot
Arguments

... 
List of plots to be arranged into the grid. The plots can be objects of one of the following classes: ggplot, recordedplot, gtable, or alternative can be a function creating a plot when called (see examples).

So, If I input a list of ggplot2 objects to plot_grid(), it should combine those plots into one, right?

So why won't this work?

p1 <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5) 
p2 <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() +
  theme(axis.text.x = element_text(angle=70, vjust=0.5))

list(p1, p2) %>% 
  map(plot_grid)

Upvotes: 1

Views: 3075

Answers (2)

Lisa DeBruine
Lisa DeBruine

Reputation: 868

You want do.call(), not map(), to pass a list of arguments to a function. For your example above:

library(ggplot2)

p1 <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5) 
p2 <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() +
  theme(axis.text.x = element_text(angle=70, vjust=0.5))

plots <- list(p1, p2)
do.call(cowplot::plot_grid, plots)

Upvotes: -1

www
www

Reputation: 39154

See the documentation of map (?map), it states that:

.x     A list or atomic vector. 
.f     A function, formula, or atomic vector.

It means the function you provided for .f will be applied to every elements in .x. So the following code

list(p1, p2) %>% map(plot_grid)

is the same as the following code

plot_grid(p1)
plot_grid(p2)

,which is probably not what you want.

What you want is probably this

plot_grid(p1, p2)

Or this

plot_grid(plotlist = list(p1, p2))

Upvotes: 6

Related Questions