R:将ggplot2图保存在列表中 [英] R: saving ggplot2 plots in a list

查看:820
本文介绍了R:将ggplot2图保存在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个R代码,允许用户从数据中选择列并绘制每个列的直方图。因此,我使用'for'循环来使用ggplot2库生成所需数量的图并将它们保存在单个列表中。但是我面临的问题是,在'for'循环的每一次迭代中,列表中的所有对象都存储相同的图。因此,最终输出由直方图的网格组成,标记不同,但是描绘了相同的(最后一个)列。



据我所知,这个问题很老,我在在for循环中重命名ggplot2图表 https://stat.ethz.ch/pipermail/r-help/2008-February/154438.html 是一个有用的出发点。



我使用R中提供的标准Swiss Fertility数据集来生成图。这里是代码: - $ / $>

  data_<  -  swiss 
data_< - na.omit(data_)

u < - c(2,3,4,5,6)
plotData < - data _ [,u]
bw <-5
plotType< ; - 'probability'

library(ggplot2)
library(gridExtra)

histogramList< - vector('list',length(u))

if(plotType =='probability')
{
for(i in 1:length(u))
{
indexDataFrame< - data。 frame(plotData [,i])
probabilityHistogram< -ggplot(indexDataFrame,aes(x = indexDataFrame [,1]))
histogramList [[i]] < - probabilityHistogram + geom_histogram(aes( y = .. density ..),binwidth = bw,color ='black',fill ='skyblue')+ geom_density()+ scale_x_continuous(names(plotData)[i])+ opts(legend.position ='none' )
}
} else
if(plotType =='frequency')
{
for(i in 1:length(u))
{
indexDataFrame< - data.frame(plotData [,i])
probabilityHistogram< - ggplot(indexDataF rame,aes(x = indexDataFrame [,1]))
histogramList [[i]] < - probabilityHistogram + geom_histogram(aes(y = .. count ..),binwidth = bw,color ='black' ,fill ='skyblue')+ geom_density()+ scale_x_continuous(names(plotData)[i])+ opts(legend.position ='none')
}
}

arg_list< - c(histogramList,list(nrow = 3,ncol = 2))
#jpeg('histogram',width = 1024,height = 968)
do.call(grid.arrange ,arg_list)
#graphics.off()

我很抱歉如果我错过了一个明显的回答在这个论坛中的问题,并且如果你能指示我这个问题,我将不胜感激。我希望我的解释清楚,如果没有,请让我知道所需的澄清。



谢谢!

解决方案

您可以通过以下方式大幅度简化您的代码:


  1. 使用构面而不是手动排列多个图
  2. 使用函数 melt 在包<$ c中融化数据$ c $> reshape2

  3. 这意味着您可以删除循环

这是完整的代码重写,没有看到循环。

  data_<  -  swiss 
data_< - na.omit(data_)

u< -c(2,3,4,5,6)
plotData< - data _ [,u]
bw < - 5
plotType< - '频率'

库(ggplot2)
库(重塑2)

mdat< - melt( plotData)

if(plotType =='probability'){
ph < - ggplot(mdat,aes(value))+
geom_histogram(aes(y = ..)密度..),binwidth = bw,color ='black',fill ='skyblue')+
geom_density()+
facet_wrap(〜variable,scales =free)
}

if(plotType ==频率'){
ph < - ggplot(mdat,aes(value))+
geom_histogram(aes(y = .. count ..),binwidth = bw,color ='black',fill ='skyblue')+
geom_density()+
facet_wrap(〜variable,scales =free)
}

print(ph)

由此产生的图形:

概率:





频率


I am writing a R code that allows users to select columns from a data and plots histograms for each of them. Hence, I am using a 'for' loop to generate the required number of plots using the ggplot2 library and save them in a single list. But the problem I am facing is that, at every iteration of the 'for' loop, all objects in the list are storing the same plot. Thus, the final output consists of a grid of histograms, labeled differently but depicting the same(last) column.

I understand that this question is quite old and I found the answers on renaming ggplot2 graphs in a for loop and https://stat.ethz.ch/pipermail/r-help/2008-February/154438.html to be a useful starting point.

I have used the standard Swiss Fertility dataset available in R to generate the plots. Here is the code:-

data_ <- swiss
data_ <- na.omit(data_)

u <- c(2, 3, 4, 5, 6)
plotData <- data_[,u]
bw <- 5
plotType <- 'probability'

library(ggplot2)
library(gridExtra)

histogramList <- vector('list', length(u))

if(plotType=='probability')
{
 for(i in 1:length(u))
 {
   indexDataFrame <- data.frame(plotData[,i])
   probabilityHistogram <- ggplot(indexDataFrame, aes(x=indexDataFrame[,1]))
   histogramList[[i]] <-  probabilityHistogram + geom_histogram(aes(y=..density..),     binwidth=bw, colour='black', fill='skyblue') + geom_density() + scale_x_continuous(names(plotData)[i]) + opts(legend.position='none')
 }
} else
if(plotType=='frequency')
{
 for(i in 1:length(u))
 {
   indexDataFrame <- data.frame(plotData[,i])
   probabilityHistogram <- ggplot(indexDataFrame, aes(x=indexDataFrame[,1]))
   histogramList[[i]] <- probabilityHistogram + geom_histogram(aes(y=..count..), binwidth=bw, colour='black', fill='skyblue') + geom_density() + scale_x_continuous(names(plotData)[i]) + opts(legend.position='none')
 }
}

arg_list <- c(histogramList, list(nrow=3, ncol=2))
#jpeg('histogram', width=1024, height=968)
do.call(grid.arrange, arg_list)
#graphics.off()

I apologize if I have missed an obvious answer to the question in this forum and shall be grateful if you could direct me towards it. I hope my explanation is clear and if not, please let me know about the clarifications required.

Thanks!

解决方案

You can vastly simplify your code by:

  1. Using facets, rather than manually arranging multiple plots
  2. Melting your data with the function melt in package reshape2
  3. This means you can remove the loop

Here is a complete rewrite of your code, with no loop in sight.

data_ <- swiss
data_ <- na.omit(data_)

u <- c(2, 3, 4, 5, 6)
plotData <- data_[,u]
bw <- 5
plotType <- 'frequency'

library(ggplot2)
library(reshape2)

mdat <- melt(plotData)

if(plotType=='probability'){
  ph <- ggplot(mdat, aes(value)) +
    geom_histogram(aes(y=..density..), binwidth=bw, colour='black', fill='skyblue') + 
    geom_density() + 
    facet_wrap(~variable, scales="free")
} 

if(plotType=='frequency'){
  ph <- ggplot(mdat, aes(value)) +
    geom_histogram(aes(y=..count..), binwidth=bw, colour='black', fill='skyblue') + 
    geom_density() + 
    facet_wrap(~variable, scales="free")
}

print(ph)

The resulting graphics:

Probability:

Frequency

这篇关于R:将ggplot2图保存在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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