2010-06-18 73 views
4

嗨百分比我有此功能,需要一個桌子和一個barplot標籤與R中的情節

prepare_labels <- function(ft){ 
    labs <- ft 
    labs <- paste(labs, "\n", sep="") 
    labs <- paste(labs, round(prop.table(ft)*100,2), sep="") 
    labs <- paste(labs, "%", sep="") 
    return(labs) 
} 

它實際上工作正常準備的標籤,但有沒有更好的方式來編寫功能,上面的代碼看起來很醜,我要寫出漂亮的代碼:-)

例如:

ft <- table(mydata$phone_partner_products) 
prepare_labels(ft) 
[1] "3752\n34.09%" "226\n2.05%" "2907\n26.41%" "1404\n12.76%" "1653\n15.02%" 
[6] "1065\n9.68%" 

回答

5

由於九月的說法是所有粘貼電話一樣,那麼你可以合併成一個單一的一個:

labs <- paste(ft,"\n",round(prop.table(ft)*100,2),"%",sep="") 
2

使用sprintf

sprintf("%d\n%2.2f%%", ft, prop.table(ft)*100) 
5

或者,使用ggplot2

ggplot(mtcars, aes(factor(cyl))) + geom_bar() + stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), vjust = -0.2, geom = "text", position = "identity") 

,並得到這樣的:

alt text http://img532.imageshack.us/img532/8201/barplotwpct.png

+0

這是相當不錯的!你知道如何用ggplot重新排序列。我有5個級別,但他們顯示在錯誤的順序。 「dont_know」, 「maybe_interesting」, 「not_interesting」, 「very_interesting」, 「very_not_interesting」 而且我想他們下令 dont_know,very_not_interesting,not_interesting,maybe_interesting,very_interesting – 2010-06-20 12:03:08

+0

當然,你可以:'ggplot(mtcars,AES (factor(cyl)))+ geom_bar()+ scale_x_discrete(limits = c(「6」,「8」,「4」))'。這裏有一個官方文檔:http://had.co.nz/ggplot2/scale_discrete.html – aL3xa 2010-06-21 00:05:51

+0

Thabk你aL3xa ...我很抱歉再次問你這個... 它的工作原理,但這一行stat_bin(aes(label = paste(round((prop.table(.. count ..)* 100),2),「%」,sep =「」))像以前一樣帶回訂單。 count)..有不同的順序。任何想法如何我們可以定義prop.table – 2010-06-21 08:52:06