I want to build a list of ggplot objects. I want to plot one variable on the x axis but plot each of the other variables in the data frame in the y. When I run the loop all of my values end up being the same as the last variable.
I'm hoping to use the grid.arrange function to plot all the graphs on one page.
My reprex:
library(ggplot2)
l <- list()
for(i in 2:11){
p <- ggplot(mtcars, aes(x = mpg, y = mtcars[,i])) + geom_smooth() + geom_point()
name <- paste("p",i,sep="_")
tmp <- list(p)
l[[name]] <- tmp
}
print(l$p_2)
print(l$p_3)
You can create a list of plots directly using
sapply
. For example:The list elements (each of which is a ggplot object) will be named after the y variable in the plot:
You can print all the plots by typing
plist
in the console. Or, for a single plot, just select the plot you want:For a situation like this, you might prefer faceting, which requires converting the data from wide to long format. You can have facets with different y scales by setting
scales="free_y"
.Subset the data frame before calling
ggplot
, and then useaes_string
to call column names as string.