0

I am trying to place data labels in the middle of stacked bars. I am following the approach in this question:1`. I can't figure out how to have the data labels in the right order. The bars are stacked series "one" on top and series "two" on the bottom but the data labels are the inverse.

library( plyr )
library( ggplot2 )
library( reshape2 )


year <- 2016:1999               
one <- c(5277,4955,4823,4565,4316,4129,3997,3515,3354,3281,2973,2713,2661,2412,2137,1787,1619,1543)             
two <-c(12865,12591,12011,11786,11429,10944,9773,9860,9325,8824,8508,8167,7289,6657,5866,5274,4819,4247)                


s <- data.frame( year , one , two )

dat <- melt(
    s ,
    id.vars = "year" )

dat <- ddply( 
    dat ,
    .(year), 
    transform, pos = cumsum(value) - (0.5 * value)
    )   

ggplot() + 
geom_bar(
    aes(y = value, x = year, fill = variable), 
    data = dat ,
    stat="identity"
    ) +  
geom_text(
    data= dat , 
    aes( x = year, y = pos, label = value) ,
    size=2.5
    )

enter image description here

Community
  • 1
  • 1
MatthewR
  • 2,660
  • 5
  • 26
  • 37
  • 1
    I have ggplot2 v2.1.0 and everything looks fine in my case. – Christoph Oct 25 '16 at 17:01
  • You could always just reverse them: `pos = rev(cumsum(value) - (0.5 * value))`. – joran Oct 25 '16 at 17:04
  • @Christoph - I just ran it using ggplot2 v2.1.0 and got what I was looking for. It appears to be an issue when using the development version: devtools::install_github("hadley/ggplot2") . Thanks – MatthewR Oct 25 '16 at 17:25

1 Answers1

2

I was using the development version devtools::install_github("hadley/ggplot2")
It turns out that the new version has an improved method to place data labels in stacked bars The code below works on the new version. As noted in the comments the code in the question does work on the version currently on cran.

library( plyr )
library( ggplot2 )
library( reshape2 )


year <- 2016:1999               
one <- c(5277,4955,4823,4565,4316,4129,3997,3515,3354,3281,2973,2713,2661,2412,2137,1787,1619,1543)             
two <-c(12865,12591,12011,11786,11429,10944,9773,9860,9325,8824,8508,8167,7289,6657,5866,5274,4819,4247)                


s <- data.frame( year , one , two )

dat <- melt(
    s ,
    id.vars = "year" )

ggplot(dat, aes(factor(year), y = value , fill = factor(variable))) +
  geom_bar( stat="identity") +
   geom_text(aes(label = value), position = position_stack(vjust = 0.5))
MatthewR
  • 2,660
  • 5
  • 26
  • 37