R: Plot multiple box plots using columns from data frame

守給你的承諾、 提交于 2019-11-27 06:03:17

问题


I would like to plot an INDIVIDUAL box plot for each unrelated column in a data frame. I thought I was on the right track with boxplot.matrix from the sfsmsic package, but it seems to do the same as boxplot(as.matrix(plotdata) which is to plot everything in a shared boxplot with a shared scale on the axis. I want (say) 5 individual plots.

I could do this by hand like:

par(mfrow=c(2,2))
boxplot(data$var1
boxplot(data$var2)
boxplot(data$var3)
boxplot(data$var4)

But there must be a way to use the data frame columns?

EDIT: I used iterations, see my answer.


回答1:


You could use the reshape package to simplify things

data <- data.frame(v1=rnorm(100),v2=rnorm(100),v3=rnorm(100), v4=rnorm(100))
library(reshape)
meltData <- melt(data)
boxplot(data=meltData, value~variable)

or even then use ggplot2 package to make things nicer

library(ggplot2)
p <- ggplot(meltData, aes(factor(variable), value)) 
p + geom_boxplot() + facet_wrap(~variable, scale="free")



回答2:


From ?boxplot we see that we have the option to pass multiple vectors of data as elements of a list, and we will get multiple boxplots, one for each vector in our list.

So all we need to do is convert the columns of our matrix to a list:

m <- matrix(1:25,5,5)
boxplot(x = as.list(as.data.frame(m)))

If you really want separate panels each with a single boxplot (although, frankly, I don't see why you would want to do that), I would instead turn to ggplot and faceting:

m1 <- melt(as.data.frame(m))
library(ggplot2)
ggplot(m1,aes(x = variable,y = value)) + facet_wrap(~variable) + geom_boxplot()



回答3:


I used iteration to do this. I think perhaps I wasn't clear in the original question. Thanks for the responses none the less.

par(mfrow=c(2,5))
for (i in 1:length(plotdata)) {
        boxplot(plotdata[,i], main=names(plotdata[i]), type="l")

}


来源:https://stackoverflow.com/questions/11346880/r-plot-multiple-box-plots-using-columns-from-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!