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

时间:2019-07-10 16:22:00

标签: r ggplot2 bar-chart

我堆叠了具有总频率的条形图,我只想在图表中添加每个类别的百分比(请参见下图的链接)。换句话说,我只想在现在报告的数字下方显示每个类别的百分比。例如,我不想在第一栏中看到“ 170”,而是希望看到“ 170(85.4%)”;我希望看到的不是“ 29”,而是“ 29(14.6%)”;等

这是我现在拥有的代码

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

谢谢!

RB。

1 个答案:

答案 0 :(得分:0)

正如A. S. K.提到的,您可以在ggplot内部或外部进行操作。 在您的特定示例中,您可以执行以下操作:

# 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()

Example