简体   繁体   中英

How to show labels of both bars in a grouped bar chart using ggplot2?

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

我的情节

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

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM