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

时间:2018-05-14 15:04:03

标签: r ggplot2 bar-chart labels

我有以下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))

percX包含protsX中相应条目的百分比值。我设法获得绝对值作为添加到栏中的文本,但是如何添加每个栏的百分比呢?

enter image description here

1 个答案:

答案 0 :(得分:0)

我想使用percent包中的scales函数:

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

Chart