0

I am using the ggplot2 package to plot a grouped bar chart. I am having a hard time trying to show the labels above each bars. It seems that my code is simply showing the sum of each group. It is may be important to point out that my dataframe df3 consist of only 3 categorical variables (hence why I am using count in the codes below).

ggplot(df3, aes(SubDept2, ..count..)) + 
  geom_bar(aes(fill = Attrition), position = "dodge")+
  geom_text(aes(label=..count..),stat='count',position=position_dodge(0.9))+
  theme_minimal()+
  scale_fill_brewer(palette="Paired")+
  labs(x="Sub Dept",y="Count")

Here is how my plot looks (cropped image):

my plot

Here is how my sample data (df3) looks like:

Attrition   Dept               SubDept2
Yes         Administration     Finance
Yes         Operations         F&B
Yes         Operations         F&B
No          Operations         Rooms Division
user3115933
  • 4,303
  • 15
  • 54
  • 94
  • 1
    Might this help? https://stackoverflow.com/questions/12018499/how-to-put-labels-over-geom-bar-for-each-bar-in-r-with-ggplot2?rq=1 Please provide example data. – Chris Aug 20 '18 at 13:27
  • Unfortunately, no because in that example, a column of values already exist. I have updated my question with sample data of data frame df3. – user3115933 Aug 20 '18 at 13:35

1 Answers1

2

Just include fill=Attrition in the original ggplot() call.

df3 <- data.frame(
  Attrition = sample(c('Yes','no'),size = 100,replace = T),
  Dept = sample(c('Administration','Operations'),size=100,replace=T),
  SubDept2 = sample(c('Finance','F&B','Rooms Division'),size=100,replace=T)
)

df3

ggplot(df3, aes(SubDept2, ..count..,,fill=Attrition)) + 
  geom_bar(aes(fill = Attrition), position = "dodge")+
  geom_text(aes(label=..count..),stat='count',position=position_dodge(0.9))+
  theme_minimal()+
  scale_fill_brewer(palette="Paired")+
  labs(x="Sub Dept",y="Count")

enter image description here

Chris
  • 3,836
  • 1
  • 16
  • 34