I am trying to figure out how to determine the midpoint values of grouped bars, i.e. the actual X positions of the center of each bar. This is easily done in the base R barplot
function, however I'd like to be able to do it in lattice's barchart
. My goal is to display the values of text column on top of the corresponding bar.
The code below allows me to place the text on top of the bars as long as I do not do use subgroups. I have tried searching Internet for the solution but nothing seems to work. As you can see from the graph, the midpoints are determined only for the center of the entire group.
Thanks!
library(lattice)
test= data.frame(
group=c("WK 1", "WK 1", "WK 1", "WK 2", "WK 2", "WK 2", "WK 3", "WK 3", "WK 3"),
subgroup=c(1,2,3,1,2,3,1,2,3) ,
percent=c(60,50,80,55,56,65,77,65,86),
text=c("n=33", "n=37","n=39","n=25","n=27","n=22","n=13","n=16","n=11")
)
barchart(data=test,
percent~group,
groups=subgroup,
panel = function(x,y,...){
panel.barchart(x, y, ...)
panel.text( x=unique(test$group),
y=test$percent,
label=unique(test$text)
)
}
)