R: Plot multiple box plots using columns from data frame

gisol picture gisol · Jul 5, 2012 · Viewed 71k times · Source

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.

Answer

Jase_ picture Jase_ · Jul 5, 2012

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