MatthewR
MatthewR

Reputation: 2770

Stacked Bars Different Order than Data labels in ggplot2

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

Upvotes: 0

Views: 195

Answers (1)

MatthewR
MatthewR

Reputation: 2770

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))

Upvotes: 2

Related Questions