R: Plot multiple box plots using columns from data frame

∥☆過路亽.° 提交于 2019-11-28 11:02:12

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

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

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

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