tej*_*ale 14 r histogram ggplot2
我正在编写一个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()
Run Code Online (Sandbox Code Playgroud)
如果我在本论坛上错过了对这个问题的明显答案,我深表歉意,如果你能指导我,我将不胜感激.我希望我的解释清楚,如果没有,请告诉我所需的澄清.
谢谢!
And*_*rie 17
您可以通过以下方式大大简化代码:
melt包中的功能融化数据reshape2这是对代码的完全重写,看不到循环.
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)
Run Code Online (Sandbox Code Playgroud)
结果图形:
可能性:

频率

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')
}
Run Code Online (Sandbox Code Playgroud)
这至少对我有用.这样可以避免必须对数据进行子集化,并允许您通过引用名称引用要绘制的列.