[R] add arrows to barchart with groups

Deepayan Sarkar deepayan.sarkar at gmail.com
Fri Apr 27 19:52:09 CEST 2007


On 4/27/07, GOUACHE David <D.GOUACHE at arvalisinstitutduvegetal.fr> wrote:
> Hello Rhelpers,
>
> I am trying to represent the following data (hereafter named donnees) in a barchart with a grouping variable :
>
>
> site    traitement      date    s       res
> 1       NT      17/10/2005      normal  76.2
> 1       T       17/10/2005      normal  103.2
> 1       NT      23/11/2005      tardif  81.6
> 1       T       23/11/2005      tardif  98
> 2       NT      15/10/2005      normal  72.71
> 2       T       15/10/2005      normal  94.47
> 2       NT      15/11/2005      tardif  79.65
> 2       T       15/11/2005      tardif  94.7
>
> barchart(res~s|site,groups=traitement,data=donnees)
>
> What I'd like to do is for each site represent with an arrow the difference in value of variable res between normal and tardif values of variable s.
> I've found one way of doing it:
>
>
> trellis.focus("panel",1,1)
> xx<-trellis.panelArgs()$x
> yy<-trellis.panelArgs()$y
> panel.arrows(as.numeric(xx)[c(1,3)]-0.1,yy[c(1,3)],as.numeric(xx)[c(1,3)]-0.1,yy[c(2,4)],lwd=2,code=3)
> panel.text(as.numeric(xx)[c(1,3)]-0.35,c(87,87),paste(yy[c(2,4)]-yy[c(1,3)],"\nq/ha"),font=2)
> trellis.focus("panel",2,1)
> xx<-trellis.panelArgs()$x
> yy<-trellis.panelArgs()$y
> panel.arrows(as.numeric(xx)[c(1,3)]-0.1,yy[c(1,3)],as.numeric(xx)[c(1,3)]-0.1,yy[c(2,4)],lwd=2,code=3)
> panel.text(as.numeric(xx)[c(1,3)]-0.35,c(87,87),paste(yy[c(2,4)]-yy[c(1,3)],"\nq/ha"),font=2)
> trellis.unfocus()
>
> But I would prefer doing this within a custom panel function so I can apply it more generally, and I haven't been able to figure out how...
> Could anyone give me a hand?

The obvious analog (just copy/pasting your code) is:

my.panel <- function(x, y, ...)
{
    panel.barchart(x, y, ...)
    xx <- x
    yy <- y
    panel.arrows(as.numeric(xx)[c(1,3)]-0.1, yy[c(1,3)],
                 as.numeric(xx)[c(1,3)]-0.1, yy[c(2,4)],
                 lwd = 2, code = 3)
    panel.text(as.numeric(xx)[c(1,3)] - 0.35, c(87,87),
               paste(yy[c(2,4)] - yy[c(1,3)], "\nq/ha"),
               font=2)
}

and this seems to work:

barchart(res~s|site,groups=traitement,data=donnees,
         panel = my.panel)

barchart(res~s|site,groups=traitement,data=donnees,
         panel = my.panel,
         origin = 0)

I'm not sure what else you are looking for and what you mean by "more
general". For example, it's not clear what you want to happen If you
have more than 2 levels in 'groups', or if the second bar is not
always higher than the first.

-Deepayan



More information about the R-help mailing list