[R] Adding labels into lattice's barchart

Deepayan Sarkar deepayan.sarkar at gmail.com
Mon Feb 14 13:49:04 CET 2011


On Mon, Feb 14, 2011 at 5:16 PM, Luca Meyer <lucam1968 at gmail.com> wrote:
> Thanks Deepayan,
>
> What you suggest is quite fine, but provides the overall number of cases for the entire dataset splitted into V2 levels.
>
> What about if I need to show panel specific's values? For instance I want to show not the total number of Female but the total number of Female in 1st Class.
>
> In other worlds, take your example and suppose I have:
>
> barchart(V2 ~ Freq | V1, data = tdf, groups = V3, layout=c(1,4), stack=TRUE,
>        ylim = sprintf("%s (n=%g)", names(numByV2), numByV2))
>
> and now what I would like to show is the result of
>
> with(tdf, tapply(Freq, list(V2,V1), sum))
>
> next to each stacked bar.
>
> In the previous example, I would need show in the Crew panel Female (n=23), in the 3rd Class panel Female (n=196), etc...
>
> Can I do that?

Well, then you probably don't want to change the labels, but rather
put in the counts in each panel. Something like

barchart(V2 ~ Freq | V1, data=tdf, groups=V3, stack=TRUE,
         panel = function(x, y, ...) {
             n <- tapply(x, y, sum)
             panel.barchart(x, y, ...)
             panel.text(x = 0, y = sort(unique(as.numeric(y))),
                        srt = 90, adj = c(0.5, -0.2),
                        labels = sprintf("(n = %g)", n))
         })

If the numbers you want to add up is not the x or y variable, then you
need a little bit more work. You will need to pass in the count
variable separately and use 'subscripts' to get the proper subsets
(look for discussions of 'subscripts' in the documentation and/or
book).

-Deepayan



More information about the R-help mailing list