Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Plot multiple box plots using columns from data frame

Tags:

r

boxplot

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.

like image 262
gisol Avatar asked Jul 05 '12 14:07

gisol


People also ask

How do you make a boxplot with multiple columns in R?

You can stack dataframe columns with the stack function. In case you need to plot a different boxplot for each column of your R dataframe you can use the lapply function and iterate over each column.

How do you make multiple box plots in R?

In this article, we will learn how to plot multiple boxplot in one graph in R Programming Language. This can be accomplished by using boxplot() function, and we can also pass in a list, data frame or multiple vectors to it. For this purpose, we need to put name of data into boxplot() function as input.

How do you make a boxplot from a Dataframe in R?

First of all, create a data frame with single numerical column and create the boxplot for that column using boxplot function. Then, create the same boxplot with show. names argument set to TRUE.

How do I make a grouped boxplot in R?

In order to create a box plot by group in R you can pass a formula of the form y ~ x , being x a numerical variable and y a categoriacal variable to the boxplot function. You can pass the variables accessing the data from the data frame using the dollar sign or subsetting the data frame.


1 Answers

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")
like image 190
Jase_ Avatar answered Oct 11 '22 21:10

Jase_