Trying to make a list of ggplot objects in a for l

2020-02-15 12:24发布

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)

标签: r ggplot2
2条回答
何必那么认真
2楼-- · 2020-02-15 12:33

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"]]

enter image description here

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)

enter image description here

查看更多
Deceive 欺骗
3楼-- · 2020-02-15 12:48

Subset the data frame before calling ggplot, and then use aes_string to call column names as string.

library(ggplot2)

l <- list()
for(i in 2:11){
  temp <- mtcars[, c(1, i)]
  p <- ggplot(temp, aes_string(x = "mpg", y = names(temp)[2])) + geom_smooth() + geom_point()
  name <- paste("p",i,sep="_")
  tmp <- list(p)
  l[[name]] <- tmp
}
print(l$p_2)

enter image description here

print(l$p_3)

enter image description here

查看更多
登录 后发表回答