how to add multiple boxplots to same axis set

418 Views Asked by At

I'm trying to plot 4 groups of data as boxplots on the same set of axis. I've been able to use the print() function to plot them on separate plots, but can't figure out how to plot them all together, preferably using the base package or lattice

below is some code I am trying, but it keeps coming up with error:

Error in x[floor(d)] + x[ceiling(d)] :
non-numeric argument to binary operator

Heres the code I'm currently trying:

Summer <- SeasonalMax$Summer
Autumn <- SeasonalMax$Autumn
Winter <- SeasonalMax$Winter
Spring <- SeasonalMax$Spring

boxplot(Summer, Autumn, Winter, Spring,
    main = "Multiple boxplots for comparision",
    at = c(1,2,3,4),
    names = c("Summer", "Autumn", "Winter", "Spring"),
    las = 2,
    col = c("red","orange", "blue", "pink"))
2

There are 2 best solutions below

2
JMilner On

First melt the data into long format

# Dummy dataset
Dat <- data.frame(Spring = runif(10,0,1),
           Summer = runif(10,0,1),
           Autumn = runif(10,0,1),
           Winter = runif(10,0,1))

Then melt the data into long format with either : reshape2 package

library(reshape2)
melt(Dat)

or tidyr package

library(tidyr)
gather(Dat,key="Season",value="Value")

Then when you plot the boxplot , use the formula argument as follows [I will continue with tidyr because I named the columns]

Dat2 <- gather(Dat,key="Season",value="Value")
with(Dat2,boxplot(Value~Season))

And with all your additions

with(Dat2,boxplot(Value~Season,
     main = "Multiple boxplots for comparision",
     at = c(1,2,4,5),
     names = c("Summer", "Autumn", "Winter", "Spring"),
     las = 2,
     col = c("red","orange", "blue", "pink")))
0
Deng Fei On

You can use ggplot2 and data.table, I think it is easier, here is the code:

library(data.table)
library(ggplot2)
dat <- data.table(Spring = c(runif(9,0,1),2),
                  Summer = runif(10,0,1),
                  Autumn = runif(10,0,1),
                  Winter = runif(10,0,1))
dat1 = melt(dat)

ggplot(data=dat1,aes(x=variable,y=value)) +geom_boxplot(outlier.colour = "red")
ggplot(data=dat1,aes(x=variable,y=value,colour=variable)) +geom_boxplot() 

boxplot by group