Search code examples
rlattice

How to add median vertical line to panels of lattice density plot?


I'm using a data frame in a long format to create a panelled density plot in lattice. Now I'd like to add a vertical line at the median x-value within each panel. I found a suggestion for doing it in an dotplot ( http://r.789695.n4.nabble.com/how-to-add-a-vertical-line-for-each-panel-in-a-lattice-dotplot-with-log-scale-td4632513.html ), but this doesn't work for me. Here is my code:

data(Chem97, package="mlmRev")

densityplot(~gcsescore | factor(score), data=Chem97,
        panel=function(...){
          panel.densityplot(...)
          median.values <- median(x) 
          panel.abline(v=median.values, col.line="red") 
        })

The error is: Object x not found. So I tried the following:

panel=function(x,...){
          panel.densityplot(...)
       }

The moment I add x as an argument to the panel function, I get the error Error using packet 1 (2, 3 etc.). x is missing.

What's going wrong?


Solution

  • I've finally found the solution:

    densityplot(~gcsescore | factor(score), data=Chem97,
        panel=function(x,...){
          panel.densityplot(x,...)
          panel.abline(v=quantile(x,.5), col.line="red") 
        })