samedi 28 mai 2016

Conditional Axis in Lattice R

Here it comes a challenge. The target is to give format (bold/regular) to the y-axis in a dotplot under de condition of variable "Z" being higher/lower sd. I have already been able to introduce the formatting so I am now struggling on how to introduce the logic test.

   #dataframe
d<-data.frame(a=LETTERS[1:26],b=rnorm(26,50,10),c=rnorm(26,50,1))
#dotplot
dotplot(a~b,d,col="blue",pch=16,
        #simple plot comparing two vectors
        panel = function(x,col,y,...){
  panel.dotplot(x,col="blue",y,...)
  panel.xyplot(x=d$c,col="darkblue",y,...)
  mins=NULL
  maxs=NULL
  #a line showing the difference between "measures"
  for(i in 1:nrow(d)){
    mins[i]<-min(d$c[i],d$b[i])
    maxs[i]<-max(d$c[i],d$b[i])
  }
  panel.segments(x0=mins,y0=as.numeric(y),
                 x1=maxs,y1=as.numeric(y),col="red")
},
#the challenge of the conditional Y-axis
yscale.components = function(...){ 
  temp <- yscale.components.default(...) 
  loc <- temp$left$labels$at 
  print( temp$left$labels$labels <-   
           sapply( temp$left$labels$labels, 
                   function(x) if(a> x){ 
                     as.expression(bquote( bold(.(x)))) 
                   }else{ 
                     as.expression(bquote(.(x)))} )) 
  temp },
#a legend
key = list(columns=2, 
           points=list(pch=16,col=c("blue","darkblue")),
           text=list(c("measure","fitted"))))

I would like to consider this an advance code, so let me hear your thoughts!

Aucun commentaire:

Enregistrer un commentaire