2014-12-21 118 views
3

我想使用ggplot使用百分比創建直方圖。我發現this answer這讓我成爲那裏的一部分。帶有%和百分比*標籤的ggplot直方圖*

不過,我也希望把一個標籤在顯示實際百分比每個直方圖條的頂部。

這裏是我的代碼,並輸出一個鏈接:

p <- ggplot(mtcars, aes(x = hp)) + 
     geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
     ## scale_y_continuous(labels = percent_format()) #version 3.0.9 
     scale_y_continuous(labels = percent) #version 3.1.0 
p <- p + stat_bin(aes(label=round((..count..)/sum(..count..),2)), geom="text", size=4) 
plot(p) 

這裏是輸出:image

不幸的是,你可以看到,數據標籤放置在非百分比位置和酒吧被「衝」下來。

有沒有辦法來改變stat_bin參數,使文本標籤實際上是在百分比欄頂部內側或馬上顯示出來(所以我棒不smushed)?

謝謝!

回答

2

你會想剛纔設置的y值的標籤,以及(並且確保你使用相同的頻段是你的吧)

library(scales) 
p <- ggplot(mtcars, aes(x = hp)) + 
     geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
     scale_y_continuous(labels = percent_format()) #version 3.0.9 
     ##scale_y_continuous(labels = percent) #version 3.1.0 
p <- p + stat_bin(aes(y=(..count..)/sum(..count..), 
    label=round((..count..)/sum(..count..),2)), 
    geom="text", size=4, binwidth = 25, vjust=-1.5) 
plot(p) 
+0

完美。謝謝。除了標籤值之外,我沒有意識到你可以指定y值。再次感謝。 – user36476