2013-08-20 151 views
5

這裏是我的簡單數據:當geom_text不合適時,如何在ggplot中放置百分比標籤?

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

在酒吧裏的情節,我想通過標籤周百分比,按職級。 問題是數據沒有排名的百分比。這個數據的結構不適合有一個。 (當然,原始數據比例子有更多的觀察)

有沒有人可以教我如何在這個圖表中標記百分比?

回答

15

我不確定我明白爲什麼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列包含給定的rank在指定的week內的相對頻率(因此可以看出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)) 

這是你想要的嗎?

enter image description here