[R] Re : Re : Adding mean line to a lattice density plot

K. Elo maillists at nic.fi
Thu Mar 8 18:05:22 CET 2012

HI again,

thanks for the replies. Unfortunately, due to my deadlines, I had no 
time to test Petr's suggestion. I will test it later. I had to figure 
out an alternate solution, so I decided to use "normal" plotting functions:

 > with(subset(ISGFINC2, as.numeric(SGENDER)==1), plot(density(PV1CIV),
   lwd=2, lty=1, ylim=c(0,.006)))
 > with(subset(ISGFINC2, as.numeric(SGENDER)==2), lines(density(PV1CIV),
   xlab="", lwd=2, lty=2))
 > abline(v=mean(ISGFINC2$PV1CIV[ as.numeric(ISGFINC2$SGENDER)==1 ],
   na.rm=T), col=2, lwd=2, lty=1)
 > abline(v=mean(ISGFINC2$PV1CIV[ as.numeric(ISGFINC2$SGENDER)==2 ],
   na.rm=T), col=2, lwd=2, lty=2)

This command sequence produced the plot I was looking for. But since the 
lattice package offers several options not available in "normal" 
plotting, I am still interested in understanding how to add elements in 
a lattice/trellis plot.

Kind regards,

08.03.2012 16:53, Petr PIKAL wrote:
> Hi
> You can use this function to add arbitrary line to already plotted lattice
> graph.
> addLine<- function(a=NULL, b=NULL, v = NULL, h = NULL, ..., once=F) {
> tcL<- trellis.currentLayout()
> k<-0
> for(i in 1:nrow(tcL))
>    for(j in 1:ncol(tcL))
>      if (tcL[i,j]>  0) {
> k<-k+1
>          trellis.focus("panel", j, i, highlight = FALSE)
> if (once) panel.abline(a=a[k], b=b[k], v=v[k], h=h[k], ...) else
> panel.abline(a=a, b=b, v=v, h=h, ...)
>          trellis.unfocus()
>          }
> }
> the usage is similar to abline in base graphics.
> addLine(h=some number)
> Regards
> Petr

More information about the R-help mailing list