[英]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. 我正在使用ggplot2
软件包绘制分组的条形图。 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). 可能需要指出的是,我的数据框df3
仅包含3个分类变量(因此,为什么我在下面的代码中使用count)。
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: 这是我的示例数据(df3)的样子:
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. 只需在原始ggplot()
调用中包含fill=Attrition
。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.