试图在for循环中列出ggplot对象;列表中的所有项目均写为循环的最后一次迭代 [英] Trying to make a list of ggplot objects in a for loop; all items in list are written as last iteration from loop

查看:55
本文介绍了试图在for循环中列出ggplot对象;列表中的所有项目均写为循环的最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个ggplot对象列表.我想在x轴上绘制一个变量,但在y数据框中绘制每个其他变量.当我运行循环时,我所有的值最终都与最后一个变量相同.

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.

我希望使用grid.arrange函数将所有图形绘制在一页上.

I'm hoping to use the grid.arrange function to plot all the graphs on one page.

我的代表:

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)

推荐答案

您可以直接使用sapply创建图表列表.例如:

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)

列表元素(每个元素都是一个ggplot对象)将以图中的y变量命名:

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"

您可以通过在控制台中键入plist来打印所有图.或者,对于单个图,只需选择所需的图:

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

在这种情况下,您可能更喜欢分面,这需要将数据从宽格式转换为长格式.通过设置scales="free_y",您可以具有不同y比例的构面.

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)

这篇关于试图在for循环中列出ggplot对象;列表中的所有项目均写为循环的最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆