简体   繁体   English

在ggplot2中的geom_bar图表中添加百分比标签

[英]Add percentage label to geom_bar chart in ggplot2

I have the following R code: 我有以下R代码:

library(ggplot2)
library(reshape2)

protsComp = c(232,62,53,56,61)
protsPart = c(238,64,54,58,62)
percComp = c(93.55,93.94,94.64,91.80,93.85)
percPart = c(95.97,96.97,96.43,95.08,95.38)
xaxis = c("Total", "Group 1", "Group 2", "Group 3", "Group 4")

cegma1 = data.frame(xaxis, Complete = c(232,62,53,56,61), Partial = c(238,64,54,58,62))
cegma.long = melt(cegma1)

ggplot(cegma.long, aes(xaxis, value, fill=variable)) +  geom_bar(position="dodge", stat="identity", color="black") +
geom_text(aes(x=xaxis, y=value, label=value, vjust=3.5), position = position_dodge(width=0.9))

With percX containing a percentage value of the corresponding entries in protsX. percX包含protsX中相应条目的百分比值。 I manage to get the absolute value as text added to the bars, but how can I add the percentages for each bar instead? 我设法将绝对值添加为条形文本,但是如何为每个条形添加百分比呢?

在此处输入图片说明

I like to use the percent function from the scales package: 我喜欢使用scales包中的percent函数:

library(ggplot2)
library(reshape2)
library(scales)

protsComp = c(232,62,53,56,61)
protsPart = c(238,64,54,58,62)
percComp = c(93.55,93.94,94.64,91.80,93.85)
percPart = c(95.97,96.97,96.43,95.08,95.38)
xaxis = c("Total", "Group 1", "Group 2", "Group 3", "Group 4")

cegma1 = data.frame(xaxis, Complete = c(232,62,53,56,61), Partial = c(238,64,54,58,62))
cegma.long = melt(cegma1)

ggplot(cegma.long, aes(xaxis, value, fill=variable)) +  
  geom_bar(position="dodge", stat="identity", color="black") +
  geom_text(aes(x=xaxis, y=value, label = percent(value/100), vjust=3.5), position = position_dodge(width=0.9))

图表

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

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