10

I would like to place the value for each bar in barchart (lattice) at the top of each bar. However, I cannot find any option with which I can achieve this. I can only find options for the axis.

4 Answers 4

21

Create a custom panel function, e.g.

library("lattice") p <- barchart((1:10)^2~1:10, horiz=FALSE, ylim=c(0,120), panel=function(...) { args <- list(...) panel.text(args$x, args$y, args$y, pos=3, offset=1) panel.barchart(...) }) print(p) 

lattice barchart with labels

Sign up to request clarification or add additional context in comments.

1 Comment

Works nicely for a single chart but does not seem to work for multiple chart groups?
0

I would have suggested using the new directlabels package, which can be used with both lattice and ggplot (and makes life very easy for these labeling problems), but unfortunately it doesn't work with barcharts.

Comments

0

Since I had to do this anyway, here's a close-enough-to-figure it out code sample along the lines of what @Alex Brown suggests (scores is a 2D array of some sort, which'll get turned into a grouped vector):

barchart(scores, horizontal=FALSE, stack=FALSE, xlab='Sample', ylab='Mean Score (max of 9)', auto.key=list(rectangles=TRUE, points=FALSE), panel=function(x, y, box.ratio, groups, errbars, ...) { # We need to specify groups because it's not actually the 4th # parameter panel.barchart(x, y, box.ratio, groups=groups, ...) x <- as.numeric(x) nvals <- nlevels(groups) groups <- as.numeric(groups) box.width <- box.ratio / (1 + box.ratio) for(i in unique(x)) { ok <- x == i width <- box.width / nvals locs <- i + width * (groups[ok] - (nvals + 1)/2) panel.arrows(locs, y[ok] + 0.5, scores.ses[,i], ...) } } ) 

I haven't tested this, but the important bits (the parts determining the locs etc. within the panel function) do work. That's the hard part to figure out. In my case, I was actually using panel.arrows to make errorbars (the horror!). But scores.ses is meant to be an array of the same dimension as scores.

I'll try to clean this up later - but if someone else wants to, I'm happy for it!

Comments

-1

If you are using the groups parameter you will find the labels in @rcs's code all land on top of each other. This can be fixed by extending panel.text to work like panel.barchart, which is easy enough if you know R.

I can't post the code of the fix here for licencing reasons, sorry.

2 Comments

What does that mean? Are you developing proprietary (which would have to be in-house to be legal) tools based on lattice? (Just curious.)
because a patched version of panel.text would a derived work. I'm always happy to post code samples that I write completely myself. Also I may have at any given time contracts with my employer which have a bearing on contributing to GPL.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.