2013-11-15 92 views
2

我想在堆積條形圖上放置百分比標籤。不過,我只想標出每個酒吧的最大3個百分比。我經歷了很多有用的帖子繼續SO(例如:123),這裏是我到目前爲止已經完成:在堆積條形圖內標記選定百分比值(ggplot2)

library(ggplot2) 
groups<-factor(rep(c("1","2","3","4","5","6","Missing"),4)) 
site<-c(rep("Site1",7),rep("Site2",7),rep("Site3",7),rep("Site4",7)) 
counts<-c(7554,6982, 6296,16152,6416,2301,0, 
      20704,10385,22041,27596,4648, 1325,0, 
      17200, 11950,11836,12303, 2817,911,1, 
      2580,2620,2828,2839,507,152,2) 
tapply(counts,site,sum) 
tot<-c(rep(45701,7),rep(86699,7), rep(57018,7), rep(11528,7)) 
prop<-sprintf("%.1f%%", counts/tot*100) 

data<-data.frame(groups,site,counts,prop) 

ggplot(data, aes(x=site, y=counts,fill=groups)) + geom_bar()+ 
    stat_bin(geom = "text",aes(y=counts,label = prop),vjust = 1) + 
    scale_y_continuous(labels = percent) 

我想在這裏插入我的輸出圖像,但不要」 t似乎有足夠的聲譽......但上面的代碼應該能夠產生情節。

那麼我怎樣才能標出每個酒吧最大的3個百分點呢?另外,對於這個傳說,我可以改變這些類別的順序嗎?例如,首先放置「丟失」。這不是一個大問題,但對於我的真實數據集來說,圖例中類別的順序真的讓我困擾。

我是這個網站的新手,所以如果有什麼不清楚我的問題,請讓我知道,我會解決它。我很欣賞任何答案/評論!謝謝!

回答

1

我以某種怪異的方式做到了這一點。這不是那麼優雅。

無論如何,我使用了plyr包,因爲拆分應用組合策略似乎是要走到這裏的路。

我用一個代表每個站點百分比的變量perc重新創建了您的數據框。然後,對於每個站點,我只保留了prop的3個最大值,並用""替換了其餘的值。

# I added some variables, and added stringsAsFactors=FALSE 
data <- data.frame(groups, site, counts, tot, perc=counts/tot, 
        prop, stringsAsFactors=FALSE) 

# Load plyr 
library(plyr) 
# Split on the site variable, and keep all the other variables (is there an 
# option to keep all variables in the final result?) 
data2 <- ddply(data, ~site, summarize, 
       groups=groups, 
       counts=counts, 
       perc=perc, 
       prop=ifelse(perc %in% sort(perc, decreasing=TRUE)[1:3], prop, "")) 

# I changed some of the plotting parameters 
ggplot(data2, aes(x=site, y=perc, fill=groups)) + geom_bar()+ 
    stat_bin(geom = "text", aes(y=perc, label = prop),vjust = 1) + 
    scale_y_continuous(labels = percent) 

enter image description here

編輯:看起來你的秤是錯在原始的繪圖代碼。它給了我y軸上的7500000%的結果,這對我來說似乎有點...

編輯:我修正了代碼。