The problem is that I have a data set where I want to plot n "y" variables against one "x" variable in ggplot2. I want to then make multiple multiplots for k levels of a factor and save all k mulitplots in one file.
For example, consider the mtcars data. I can generate a figure of y=hp vs. x=mph and a separate figure of y=wt vs. x=mph and put them together into one multiplot by:
library(dplyr)
library(ggplot2)
library(gridExtra)
library(cowplot)
a1 <- ggplot(mtcars,aes(mpg,hp))+geom_point()
b1 <- ggplot(mtcars,aes(mpg,wt))+geom_point()
p <- grid.arrange(a1,b1)
OK, now I want to create the same multiplot but for different levels of the factor "am". (Edit: I would like to have one multiplot for am=0 and one multiplot for am=1) I found a solution for creating plots based on a factor and saving in one file [here]How subset a data frame by a factor and repeat a plot for each subset?
I tried to modify the above code for my problem, the following is my attempt:
plots = mtcars %>%
group_by(am) %>%
do({a = a1 %+% .
b = b1 %+% .
plots = p %+% .})
I also tried:
plots = mtcars %>%
group_by(am) %>%
do({a1 = ggplot(.,aes(mpg,hp))+geom_point()
b1 = ggplot(.,aes(mpg,wt))+geom_point()
p = grid.arrange(a1,b1)})
in both situations I have the error
Error: Results are not data frames at positions: 1, 2
I understand that there is a data frame problem. But I don't understand why it is a problem in my code and not in the sample code. Any help is appreciated! Thanks in advance.
EDIT:
Following Tims post below, gather can be used to achieve the end result that I am looking for.
library(tidyr)
dat1 <- mtcars %>%
gather(key, value, hp, wt)
p <- ggplot(dat1,aes(mpg, value)) +
geom_point() +
facet_wrap(~ key, scales = "free_y")
plots = dat1 %>%
group_by(am) %>%
do(
plots = p %+% .)
pdf()
plots$plots
dev.off()
However, this doesn't allow much in the way of customization for the individual plots for different variables. Say I wanted to add a line using geom_vline to plot hp vs. mpg but not have it on plot wt vs. mpg. I'm not sure you could do that in this method.