1

I'm using some of the ideas from here. I would like to draw a box on top of the lattice bwplot.

I would like to combine the solution provided with boxplot on lattice bwplot. Ideal pure lattice bwplot solution.

Sample data:

rdata <- data.frame(y=rnorm(1000,2,2),v1=rnorm(1000,1,1),v2=rnorm(1000,3,3),
                      v3=rnorm(1000,4,4),v4=rnorm(1000,5,5),v5=rnorm(1000,3,3))

I would like to plot a box on top of bwplot, here is a boxplot solution:

 p <- par(mfrow=c(3,2))
  for(i in 1:6){
    boxplot(rdata[,i],horizontal=TRUE,axes=FALSE)
    rect(min(rdata[,i]),1.5,quantile(rdata[,i],0.25),1.4,col="red")
    rect(quantile(rdata[,i],0.25),1.5,quantile(rdata[,i],0.60),1.4,col="green")
    rect(quantile(rdata[,i],0.60),1.4,max(rdata[,i]),1.5,col="yellow")
  }
  par(p)

How to do the same within lattice bwplot? It is possible at all? Thanks!

Just to give some starting point for the bwplot:

library(lattice)
library(gridExtra)    
plot1 <- lapply(1:2, function(i) {bwplot(~rdata[,i],rdata)})
plot2 <- lapply(1:3, function(i) {bwplot(~rdata[,i],rdata)})
plot3 <- lapply(1:4, function(i) {bwplot(~rdata[,i],rdata)})

print(do.call(grid.arrange, c(plot1,plot2,plot3)))
Community
  • 1
  • 1
Maximilian
  • 4,177
  • 7
  • 46
  • 85

1 Answers1

2

Here we can make a help function that can generate a panel function that we can use to add the colored box to the box plot

getPanelBoxCol<-function(cuts, colors=c("red","green","yellow"), yat=1.5) {
    require(grid)
    cuts<-sort(unique(c(0, cuts, 1)))
    function(x, y, ...) {
        xbr <- quantile(x, cuts)
        xx<-rowMeans(embed(xbr,2))
        yy<-rep(yat, 3)
        grid.rect(x=xx,
            y=yy, 
            width=diff(xbr),
            height=.1,
            gp=gpar(fill=colors),
            default.units="native"
        )
    }
}

Then we can create one for the cut points we want.

panel.boxcol<-getPanelBoxCol( c(0, .25, .6, 1) )

Then we can use it in the bwplot panel function

rdata<-data.frame(
    y=rnorm(100,2,2)
)
bwplot(~y,rdata, 
    prepanel=function(x,y,...) {
        list(ylim=c(.5, nlevels(y)+.6), xlim=lattice:::scale.limits(x))
    }, 
    panel=function(x,y,...) {
        panel.bwplot(x,y,...)
        panel.boxcol(x,y,...)
    },
    scales=list(y=list(draw=F))
)

Here we also added a bit of room to the y axis to accommodate the box. This results in

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295