I would like to create multiple plots at one page, where I am iteration over different Y variables over the same X. = i.e. I want one plot per one Y. Usually, I would copy and paste my ggplot
with just changed Y value, store individual plots as p.y1, p.y2
and plot all of them using grid.arrange(p.y1, p.y2)
like here:
This approach is not very fun when I have 10 different Y variables, and I want to plot all of them. I wonder how to make the process more efficient?
I thought that I can simply create a vector of Y (colnames of df
) and then loop through them to create multiple plots. But, it seems that my output plots are not correct to pass to grid.arrange()
, and I can not plot them neither.
How can I loop through multiple Ys, and then arrange all plots on one page? As I do not have multiple factors, I probably cannot use facet_grid
nor facet_wrap
.
Here is my dummy example for two Ys: y1 and y2
set.seed(5)
df <- data.frame(x = rep(c(1:5), 2),
y1 = rnorm(10)*3+2,
y2 = rnorm(10),
group = rep(c("a", "b"), each = 5))
# Example of simple line ggplot
ggplot(df, aes(x = x,
y = y2, # here I can set either y1, y2...
group = group,
color = group)) +
geom_line()
Now, iterate over the vectors of Ys and store output plots in a list:
# create vector of my Ys
my.s<-c("y1", "y2")
# Loop over list of y to create different plots
outPlots<- list()
for (i in my.s) {
print(i)
my.plot <-
ggplot(df, aes_string(x = "x",
y = i,
group = "group",
color = "group")) +
geom_line()
# print(plot)
outPlots <- append(outPlots, my.plot)
}
Intendent plotting of multiple graphs on one page: does not work because of Error in gList(list(data.x1 = 1L, data.x2 = 2L, data.x3 = 3L, data.x4 = 4L, : only 'grobs' allowed in "gList"
grid.arrange(outPlots)