R:节省GGPLOT2地块在列表(R: saving ggplot2 plots in a list

2019-06-26 02:40发布

我写A R代码,允许用户选择从数据和图表直方图柱为他们每个人。 因此,我使用的是“for”循环生成所需的数量使用GGPLOT2库地块,并将它们保存在一个单独的列表。 但我面临的问题是,在“for”循环的每次迭代,列表中的所有对象都存储相同的情节。 因此,最终输出由直方图的网格的,标记的不同,但描绘同一(最近)柱。

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

我已经使用可用的标准瑞士生育率数据集R中产生的地块。 下面是代码: -

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()

我很抱歉,如果我错过了一个明显的答案,在这个论坛的问题,并应请将我直接向它。 我希望我的解释是明确的,如果没有,请让我知道需要澄清。

谢谢!

Answer 1:

您可以大大简化通过你的代码:

  1. 使用方面,而不是手动设置多条曲线
  2. 与功能融数据melt在包reshape2
  3. 这意味着您可以消除环路

这里是你的代码完全重写,在视线没有循环。

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)

生成的图形:

可能性:

频率



Answer 2:

而不是使用映射美学的aes ,你可能会关闭使用更好的aes_string

 for(i in 1:length(u))
 {
   probabilityHistogram <- ggplot(plotData, aes_string(x=names(plotData)[i]))
   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')
 }

这工作对我来说,至少。 这避免了子集的数据,并允许您引用您想要引用名称来绘制列。



文章来源: R: saving ggplot2 plots in a list