0

I am in the process of creating a stacked percentage bar chart. I can make the bar chart, but when I add text labels (using geom_label) they were not in the correct spot. Therefore I used position=position_stack(vjust=0.5) to fix it. However in doing so, the labels are not in the right spot and should be flipped. I also need to make it work when I flip the coordinates with coord_flip().

I have seen many examples and this is not a duplicate because I have tried it their way, but it did not work. Here is what I have used first, second, third. The third one uses a geom_col as well.

Code:

Type<-c('A','B','C','D','E','F')
Class<-c('Excellent','VG','G','Avg','B','VB','Poor')
example.df<-data.frame(expand.grid(Type,Class))
example.df<-example.df[order(example.df$Var1),]
example.df$per<-c(
  0.264866156,
  0.536245414,
  18.46247368,
  61.950457,
  18.57753848,
  0.206248236,
  0.002171034,
  0.078446754,
  0.349088056,
  19.51559129,
  61.38066288,
  18.50951167,
  0.166699353,
  0,
  0.760913096,
  0.52062475,
  14.45734882,
  66.51982379,
  17.66119343,
  0.080096115,
  0,
  1.110666035,
  1.55493245,
  7.882087324,
  70.66385055,
  18.70288773,
  0.074651324,
  0.010924584,
  1.505981129,
  2.423019706,
  6.576185527,
  74.43296448,
  15.01294043,
  0.048908724,
  0,
  1.779324382,
  2.695249664,
  9.435015265,
  71.38308,
  14.69091625,
  0.013131545,
  0.003282886
)

p<-ggplot()+
  geom_bar(data=example.df,aes(x=Var1,y=per,fill=Var2),stat="identity")+
  geom_label(data=example.df[example.df$per>3,],aes(x=Var1,y=per,label=paste0(round(per,1),'%')),
             position = position_stack(vjust=0.5)
  )
p
Jack Armstrong
  • 1,182
  • 4
  • 26
  • 59
  • 3
    Since you didn't set your aesthetics globally you don't have a variable to represent your stacks in `geom_label()`. This is the variable you passed to `fill`; note in at least the last 2 of your links the answer has `fill` in `ggplot()`. One option is to add `group = Var2` to `aes()` for your label layer. – aosmith Jun 26 '19 at 18:41
  • Sounds like an answer to me.... – Jack Armstrong Jun 26 '19 at 18:44

0 Answers0