簡體   English   中英

在ggplot2中的geom_bar圖表中添加百分比標簽

[英]Add percentage label to geom_bar chart in ggplot2

我有以下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中相應條目的百分比值。 我設法將絕對值添加為條形文本,但是如何為每個條形添加百分比呢?

在此處輸入圖片說明

我喜歡使用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