循环内使用ggplot2的直方图 [英] Histograms using ggplot2 within loop

查看:46
本文介绍了循环内使用ggplot2的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用loop和ggplot2创建一个直方图网格.说我有以下代码:

I would like to create a grid of histograms using a loop and ggplot2. Say I have the following code:

library(gridExtra)
library(ggplot2)

df<-matrix(NA,2000,5)
df[,1]<-rnorm(2000,1,1)
df[,2]<-rnorm(2000,2,1)
df[,3]<-rnorm(2000,3,1)
df[,4]<-rnorm(2000,4,1)
df[,5]<-rnorm(2000,5,1)
df<-data.frame(df)

out<-NULL

for (i in 1:5){

  out[[i]]<-ggplot(df, aes(x=df[,i])) + geom_histogram(binwidth=.5)

}

grid.arrange(out[[1]],out[[2]],out[[3]],out[[4]],out[[5]], ncol=2)

请注意,尽管已将df的每个列均设置为具有不同的均值,但所有图均出现,但均值和形状均相同.

Note that all of the plots appear, but that they all have the same mean and shape, despite having set each of the columns of df to have different means.

似乎只绘制了最后一个图(out [[5]]),也就是说,循环似乎正在用out [[5]]重新分配所有out [[i]] s.

It seems to only plot the last plot (out[[5]]), that is, the loop seems to be reassigning all of the out[[i]]s with out[[5]].

我不确定为什么,有人可以帮忙吗?

I'm not sure why, could someone help?

推荐答案

我同意@GabrielMagno的观点,这是可行的方法.但是,如果由于某种原因您需要使用循环,那么这些方法中的任何一个都可以完成工作.

I agree with @GabrielMagno, facetting is the way to go. But if for some reason you need to work with the loop, then either of these will do the job.

library(gridExtra)
library(ggplot2)

df<-matrix(NA,2000,5)
df[,1]<-rnorm(2000,1,1)
df[,2]<-rnorm(2000,2,1)
df[,3]<-rnorm(2000,3,1)
df[,4]<-rnorm(2000,4,1)
df[,5]<-rnorm(2000,5,1)
df<-data.frame(df)

out<-list()
for (i in 1:5){
   x = df[,i]
   out[[i]] <- ggplot(data.frame(x), aes(x)) + geom_histogram(binwidth=.5)
}
grid.arrange(out[[1]],out[[2]],out[[3]],out[[4]],out[[5]], ncol=2)

out1 = lapply(df, function(x){
   ggplot(data.frame(x), aes(x)) + geom_histogram(binwidth=.5) })
grid.arrange(out1[[1]],out1[[2]],out1[[3]],out1[[4]],out1[[5]], ncol=2)

这篇关于循环内使用ggplot2的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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