How do I add median values as text to bwplot?

900 Views Asked by At

I have a large data frame. Here is sample data (first few observation).

   Year ComplaintCategory   Days    Loop
  FY07-09    Service          1     Short
  FY07-09    Service         22     Short
  FY07-09    Product         15     Long
  FY07-09    Product          6     Long
  FY07-09    Product          6     Long
  FY07-09    Service          3     Short

I want to display only median values on conditional boxplot. Median values corresponding to each boxplot are calculated and stored in a vector CalculatedMedian. The median values are given below.

12.0 26.0 13.5 17.0 20.0 48.0 35.0 21.0 NA NA 0.0 NA NA 29.0 30.0 19.0

How do I print only median values in each panel and for corresponding boxplot at location of median?

bwplot(Days ~ Loop | factor(Year), 
   ProductData, layout = c(8, 1), pch = rep("|", 2),
   ylim = c(-10,100), scales=list(y = list(at=seq(0, 100,10))),
   main=list(label="", cex=1.4),
   ylab=list(label="Settlement Days", cex=1.3),
   xlab=list(label="Loop", cex=1.3),
 par.settings = list( box.rectangle = list(col= "black",lwd=1.3,lty=1),
                        box.umbrella = list(col= "black",lwd=1.3,lty=1),
                        ylim = seq(0, 100, by=10),
                        plot.symbol = list(col='black')),
     panel=function(x, y,...) {
           panel.abline(v = x, h = seq(0, 100, by = 10), 
                        col = "lightgrey",lty = 2,lwd=1)               
           panel.bwplot(x, y,fill=c('lemonchiffon1','lavenderblush1'),...)
           panel.text(x = x, y =CalculatedMedian, labels = CalculatedMedian)}

Below is the output of the code:

enter image description here

1

There are 1 best solutions below

0
Johan Larsson On

Here's a minimal example using some test data. If you want a solution with your original data, please provide a reproducible example.

Here we're creating a vector of medians in the call and then plot them using the coordinates obtained from the medians.

dd <- data.frame(
  x = rnorm(100),
  ind = as.factor(rbinom(100, 3, 1/3))
)

bwplot(x ~ ind, data = dd, md = tapply(dd$x, dd$ind, median),
       panel = function(x, y, md, ...) {
         panel.bwplot(x, y, ...)
         panel.text(x = 1:4, y = md, labels = round(md, 2), pos = 3)
       })

Imgur