[R] barchart (lattice) with text labels

Mark Lyman mark.lyman at gmail.com
Sun Feb 25 10:17:37 CET 2007


Deepayan Sarkar wrote:
> On 2/24/07, Mark and Heather Lyman <lymanmh at xmission.com> wrote:
>> I would like to place the value for each bar in barchart (lattice) at
>> the top of each bar. Something like the following code produces.
>>
>> library(lattice)
>>
>> mypanelfunc <- function(x, y, ...)
>> {
>>   panel.barchart(x, y, ...)
>>   panel.text(x, y, labels=as.character(round(x,2)), ...)
>>   }
>>
>> myprepanelfunc <- function(x, y, ...) list(xlim=c(0, max(x)+.1))
>>
>> mydata <- expand.grid(a=factor(1:5), b=factor(1:3), c=factor(1:2))
>> mydata$x <- runif(nrow(mydata))
>>
>> barchart(a~x|b, mydata, groups=c, panel=mypanelfunc,
>> prepanel=myprepanelfunc, adj=c(-0.1,0.5))
>>
>> However, I cannot figure out how to shift the values to correspond with
>> their respective grouped bar.
>
> You should look at panel.barchart and try to reproduce the
> calculations done there.
>
> Deepayan
>
This is the panel function that I ended up using. As Deepayan suggested, 
I borrowed heavily from panel.barchart.

mypanelfunc <- function(x, y, groups, box.ratio, ...)
{
  panel.barchart(x, y, groups=groups, box.ratio=box.ratio, ...)
  origin <- current.panel.limits()$xlim[1]
  groupSub <- function(groups, subscripts, ...) groups[subscripts]
  groups <- as.numeric(groupSub(groups, ...))
  vals <- sort(unique(groups))
  nvals <- length(vals)
  height <- box.ratio/(1+ nvals * box.ratio)
  for (i in unique(y)) {
    ok <- y == levels(y)[i]
    nok <- sum(ok, na.rm = TRUE)
    panel.text(x = x[ok], y = (i + height * (groups[ok] - (nvals + 1)/2)),
      labels=as.character(signif(x[ok],2)), ...)
  }
}

Mark Lyman



More information about the R-help mailing list