You can create a list of plots directly using sapply
. For example:
plist = sapply(names(mtcars)[-grep("mpg", names(mtcars))], function(col) {
ggplot(mtcars, aes_string(x = "mpg", y = col)) + geom_smooth() + geom_point()
}, simplify=FALSE)
The list elements (each of which is a ggplot object) will be named after the y variable in the plot:
names(plist)
[1] "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"
You can print all the plots by typing plist
in the console. Or, for a single plot, just select the plot you want:
plist[["hp"]]
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"
.
library(tidyverse)
ggplot(gather(mtcars, key, value, -mpg), aes(mpg, value)) +
geom_smooth() + geom_point() +
facet_wrap(~ key, scales="free_y", ncol=5)