1

I, here is my problem.

I'd like to make a geom_bar with ggplot2, with label on the bars.

Here is a reproducible exemple and the plot which is generated:

prop = c(rep("A",2),rep("B",2),rep("C",2))
n = c(rep(29,2),rep(63,2),rep(25,2))
var = c(rep(c("sortant","entrant"),3))
value = c(10,19,43,20,10,15)
mydata = data.frame(cbind(prop,n,var,value))

> mydata
prop  n     var value
   A 29 sortant    10
   A 29 entrant    19
   B 63 sortant    43
   B 63 entrant    20
   C 25 sortant    10
   C 25 entrant    15

mydata$n = as.integer(as.character(mydata$n))
mydata$value = as.integer(as.character(mydata$value))

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value))

enter image description here

I would like to produce this plot, without creating "y_pos" manually (like the exemple following) because I'have to make this plot every week with different data.

mydata2 = mydata
mydata2$y_pos = c(7,20,20,50,7,17)

>mydata2
prop  n     var value y_pos
   A 29 sortant    10     7
   A 29 entrant    19    20
   B 63 sortant    43    20
   B 63 entrant    20    50
   C 25 sortant    10     7
   C 25 entrant    15    17

ggplot(data = mydata2)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value, y = y_pos))

With this code, I have the plot that I want, but I don't want to make some variables manually :

enter image description here

If it is possible, how can I make this plot :

  • with good values

  • in the right order

  • in the right place ?

Thanks in advance, any help or exemple is appreciable !

NB: (I don't want use position_dodge(), I want to keep this format)

MBnnn
  • 308
  • 2
  • 13
  • Actually, [this target is better](https://stackoverflow.com/questions/6644997/showing-data-values-on-stacked-bar-chart-in-ggplot2/6645506#6645506). – Axeman Jun 08 '17 at 14:19
  • Thanks, @GGamba gave me the same solution ! – MBnnn Jun 08 '17 at 14:30
  • I know ;). But there's a policy here to close duplicate questions so they are linked together. That means that it is easier to for people to find the original answer, which is more likely to be updated if necessary. – Axeman Jun 08 '17 at 14:33

1 Answers1

5

You can use the position argument inside geom_text with position_stack():

library(ggplot2)

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+
    geom_col()+
    scale_fill_brewer(palette = 'Paired')+
    geom_text(aes(label = value), position = position_stack(vjust = .5))

GGamba
  • 13,140
  • 3
  • 38
  • 47
  • Worked perfectly. Thank you so much, I'm sorry I didn't found this solution and I wasn't expecting it was as simple as that. Thanks ! – MBnnn Jun 08 '17 at 14:07