简体   繁体   English

如何在ggplot2中使用总频率和百分比创建堆叠的条形图

[英]How to create a stacked bar chart in ggplot2 with total frequency AND percentages

I have stacked bar charts with total frequency, and I simply want to add the percentage for each category in the graph (see link with image below). 我堆积了条形图和总频率,我只想在图表中添加每个类别的百分比(请参见下面的链接)。 In other words, I just want to show the percentage for each category below the number that is now reported. 换句话说,我只想在现在报告的数字下方显示每个类别的百分比。 For example, instead of seeing "170" in the first bar, I would like to see "170 (85.4%)"; 例如,我不想在第一栏中看到“ 170”,而是希望看到“ 170(85.4%)”; instead of "29", I would like to see "29 (14.6%)"; 我希望看到的不是“ 29”,而是“ 29(14.6%)”; etc. 等等

This is the code I have now 这是我现在的代码

networkmeasured <- data.frame(supp=rep(c("Article measures network", 
"Article does not measure network"), each=2), Type=rep(c("loosely about 
collab. gov.", "striclty about colla. gov"),2), Articles=c(29, 44, 170, 96))
head(networkmeasured)

#plotting the graph
ggplot(data=networkmeasured, aes(x=Type, y=Articles, fill=supp)) +
geom_bar(stat="identity")+
geom_text(aes(label=Articles), vjust=2, color="white", size=4)+
theme_minimal()

Thanks in advance! 提前致谢!

RB. RB。

As ASK has mentioned, you can do it either inside or outside of ggplot. 正如ASK所提到的,您可以在ggplot内部或外部进行操作。 In your particular example, you could do something like this: 在您的特定示例中,您可以执行以下操作:

# summarising the data
networkmeasured2 <- networkmeasured %>% 
  group_by(Type, supp) %>% 
  summarise(Articles = sum(Articles)) %>% 
  mutate(perc = round(Articles/sum(Articles)*100, 2))

# plotting the graph  
ggplot(data=networkmeasured2, aes(x=Type, y=Articles, fill=supp)) +
geom_bar(stat="identity") +
geom_text(aes(label = paste0(Articles, " (", perc, "%)")), vjust=2, color="white", size=4) +
theme_minimal()

例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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