Reputation: 653
I am trying to grid.arrange()
several ggplots which I need to call/evaluate from a string of text. However, I am failing miserably - only the last plot is plotted (p4
in the example case below).
library(ggplot2)
library(gridExtra)
p <- ggplot(data = mtcars, aes(x = mpg, y = wt, color = cyl))
p1 <- p + geom_point()
p2 <- p + geom_histogram()
p3 <- p + geom_dotplot()
p4 <- p + geom_smooth(method='lm')
tx <- paste0("p", 1:4)
grid.arrange(grobs = list(eval(parse(text = tx))), nrow = 2)
How can I fix this?
Upvotes: 1
Views: 186
Reputation: 124183
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'
Upvotes: 2