当geom_text不适用时,如何在ggplot中加入百分比标签?

7

以下是我简化后的数据:

company <-c(rep(c(rep("company1",4),rep("company2",4),rep("company3",4)),3))
product<-c(rep(c(rep(c("product1","product2","product3","product4"),3)),3))
week<-c( c(rep("w1",12),rep("w2",12),rep("w3",12)))

mydata<-data.frame(company=company,product=product,week=week)
mydata$rank<-c(rep(c(1,3,2,3,2,1,3,2,3,2,1,1),3))
mydata=mydata[mydata$company=="company1",]

同时,我使用的R代码:

ggplot(mydata,aes(x = week,fill = as.factor(rank))) +
geom_bar(position = "fill")+
scale_y_continuous(labels = percent_format())

在条形图中,我想按周、按等级标注百分比。问题在于数据没有等级的百分比。并且这个数据的结构不适合有一个百分比。 (当然,原始数据比示例数据多得多)。有人能教我如何在这个图表中标注百分比吗?
1个回答

18

我不确定我理解为什么geom_text不适合。这里有一个使用它的答案,但如果你指出它为什么不适合,也许会有人想出你正在寻找的答案。

library(ggplot2)
library(plyr)

mydata = mydata[,c(3,4)] #drop unnecessary variables
data.m = melt(table(mydata)) #get counts and melt it

#calculate percentage:
m1 = ddply(data.m, .(week), summarize, ratio=value/sum(value)) 

#order data frame (needed to comply with percentage column):
m2 = data.m[order(data.m$week),]

#combine them:
mydf = data.frame(m2,ratio=m1$ratio)
这给出了以下数据结构。`ratio`列包含特定`week`内给定`rank`的相对频率(因此可以看出`rank == 3`比其他两个排名多两倍)。
> mydf
  week rank value ratio
1   w1    1     1  0.25
4   w1    2     1  0.25
7   w1    3     2  0.50
2   w2    1     1  0.25
5   w2    2     1  0.25
8   w2    3     2  0.50
3   w3    1     1  0.25
6   w3    2     1  0.25
9   w3    3     2  0.50

接下来,我们需要计算百分比标签的位置并绘制它。

#get positions of percentage labels:
mydf = ddply(mydf, .(week), transform, position = cumsum(value) - 0.5*value) 

#make plot
p =
ggplot(mydf,aes(x = week, y = value, fill = as.factor(rank))) +
  geom_bar(stat = "identity")

#add percentage labels using positions defined previously
p + geom_text(aes(label = sprintf("%1.2f%%", 100*ratio), y = position))

这是您想要的吗?

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接