R - boxplot with multiple factor shortcuts

I am working on creating a box in an R-crane, which is classified by two different factors along the x axis. My problem is to create labels for one factor with +20 levels, which covers the entire chart accordingly, when using a legend to indicate a second factor, which has only 2-3 levels.

Here is a test script that roughly imitates my actual dataset:

d<-data.frame(x=rnorm(1500),f1=rep(seq(1:20),75),f2=rep(letters[1:3],500)) # first factor has 20+ levels d$f1<-factor(d$f1) # second factor a,b,c d$f2<-factor(d$f2) boxplot(x~f2*f1,data=d,col=c("red","blue","green"),frame.plot=TRUE,axes=FALSE) # y axis is numeric and works fine yts=pretty(d$x,n=5) axis(2,yts) # I know this doesn't work; what I'd like is to spread the factors out # so the each group of three(a,b,c) is labeled correctly axis(1,at=seq(1:20)) # Use the legend to handle the f2 factor labels legend(1, max(d$x), c("a", "b","c"),fill = c("red", "blue","green")) 

Thanks for any help

+7
source share
2 answers

FWIW, a ggplot2 solution:

 library(ggplot2) ggplot(data = d, aes(x = f1, y = x)) + geom_boxplot(aes(fill = f2), width = 0.8) + theme_bw() 

enter image description here

+13
source

If you need a label in the middle of each group of three fields, try something like this:

 axis(1,at=seq(2,60,3),labels=1:20,cex.axis=0.7) 

enter image description here

To summarize, this will be:

 groups <- 20 numbox <- 3 total <- groups * numbox xpoints <- seq(median(1:numbox),total,numbox) 
+5
source

All Articles