11
votes

I'm attempting to place labels on a stacked bar plot using this approach (though if there's now a better approach I'm open to what ever):

Showing data values on stacked bar chart in ggplot2

Here's my original plot:

dat <- data.frame(with(mtcars, table(cyl, gear)))

ggplot(dat, aes(x = gear, fill = cyl)) +
    geom_bar(aes(weight=Freq), position="stack") +
    geom_text(position = "stack", aes(x = gear, y = Freq, 
        ymax = 15, label = cyl), size=4)

enter image description here

Here's my attempt to center labels in each fill section:

dat2 <- ddply(dat, .(cyl), transform, pos = cumsum(Freq) - 0.5*Freq)

library(plyr)
ggplot(dat2, aes(x = gear, fill = cyl)) +
    geom_bar(aes(weight=Freq), position="stack") +
    geom_text(position = "stack", aes(x = gear, y = pos, 
        ymax = 15, label = cyl), size=4)

enter image description here

How can I center the labels in each fill section?

2

2 Answers

10
votes

There's some extraneous ddply action going on with this one as I knew the solution I wanted but was having trouble keeping the frequencies aligned with the positions, but I think the algorithm for finding the group midpoints is worth posting:

group_midpoints = function(g) {
  cumsums = c(0, cumsum(g$Freq))
  diffs = diff(cumsums)
  pos = head(cumsums, -1) + (0.5 * diffs)
  return(data.frame(cyl=g$cyl, pos=pos, Freq=g$Freq))
}

dat3 = ddply(dat, .(gear), group_midpoints)

ggplot(dat3, aes(x = gear, fill = cyl)) +
  geom_bar(aes(weight=Freq), position="stack") +
  geom_text(position = "identity", aes(x = gear, y = pos, ymax = 15, label = cyl), size=4)

enter image description here

-1
votes

I trying to do the same thing. So I tried your code with the same data and it doesn't, maybe there has been an update that changed something.

Can someone check if the code still works?

I tried using this code but doenter code hereesn't seem to work.

dd <- ggplot_build(p)[[1]][[1]]
## Get the y-values in the middle of bars
xy <- unique(dd[dd$y != 0, c("x", "y")])
dat <- with(xy, data.frame(
       x=x,
       y=unlist(sapply(split(y, x), function(z) diff(c(0, z))/2 + head(c(0, z), -1)))
))

## Get the labels
labels <- with(df[df$y!=0,], unlist(split(MaskID, x)))

## Add the text using the new xy-values and labels
p + geom_text(data=dat, aes(x, y), label=labels, angle=90)