2014-09-02 246 views
0

我有一個數據集,其中包含如下所示的二進制變量。在ggplot中顯示百分比酒吧

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5) 
M4 <- as.data.frame(M4) 
M4$id <- 1:20 

我已經產生下面

library(reshape) 
library(ggplot2) 
library(scales) 
M5 <- melt(M4, id="id") 
M5$value <- as.factor(M5$value) 
ggplot(M5, aes(x = variable)) + geom_bar(aes(fill = value), position = 'fill') + 
    scale_y_continuous(labels = percent_format()) 

使用的代碼的堆疊柱狀圖現在我想顯示在圖表中每個條的每個字段的百分比,使得每個杆達到100% 。我試過1,2,3和幾個類似的問題,但我找不到適合我的情況的任何示例。我怎樣才能管理這個任務?

回答

1

您可以使用sjp.stackfrq功能來自sjPlot-package(參見examples here)。

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5) 
M4 <- as.data.frame(M4) 
sjp.stackfrq(M4) 
# alternative colors: sjp.stackfrq(M4, barColor = c("aquamarine4", "brown3")) 

enter image description here

情節的外觀可以用各種參數custzomized ...

2

試試這個方法:

test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
    geom_bar() + 
    scale_y_continuous(labels = percent_format()) + 
    stat_bin(aes(label=paste("n = ",..count..)), vjust=1, geom="text") 
test 

enter image description here

編輯:給予百分比和使用scale小號包:

require(scales) 
test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
    geom_bar() + 
    scale_y_continuous(labels = percent_format()) + 
    stat_bin(aes(label = paste("n = ", scales::percent((..count..)/sum(..count..)))), vjust=1, geom="text") 
test 

enter image description here

+0

這看起來並不像PRECENTAGE對我來說,你可能要像'貼(圓((..數..)/總和(..計數。 。)* 100),「%」)'(而不是'paste(「n =」,.. count ..)') – 2014-09-02 10:06:52

+0

非常感謝您的幫助! 工作得很好,但我正在尋找百分比;也許你可以給一些建議呢? 將不勝感激。 – 2014-09-02 10:08:16

+0

@Arenburg:該代碼返回整個圖表的累積百分比,而不是每個小節。換句話說,所有酒吧中的所有字段總共加起來爲100%,而我需要每個酒吧加起來達到100%。 – 2014-09-02 10:24:32

0

我真的很喜歡的是由ggplot本身產生的隱含信息的使用,因爲在這個職位描述:

using the ggplot_build() function

從我的角度來看,這提供了很多機會來最終控制ol ggplot圖表的外觀。

希望這有助於在某種程度上

湯姆