2016-05-03 102 views
3

,我在下面的腳本策劃所謂的「中止」二項式變量(0/1)二項變量百分比柱狀圖:如何繪製與GGPLOT2

`ggplot(sab2, aes(x=locality,fill=factor(aborted))) + geom_bar() + scale_fill_manual() + scale_fill_grey(labels = c("aborted","alive")) + xlab("") + ylab("N empty fruits per plant") + guides(fill=guide_legend(title="Fruits vitality")) + facet_grid(~year) + theme_bw() + theme(legend.position = "bottom", panel.background = element_rect(fill = "white"), panel.grid.major = element_line(colour = "white"), axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))`  

,這是結果:

enter image description here

如果我想只繪製中止的百分比(「中止」因子的「0」水平),我可以在代碼中更改哪些內容? 我能獲得類似如下(但%的中止)一個情節:

enter image description here

謝謝!

回答

3

使用stat_summary計算的aborted平均值,這僅僅是當aborted承擔的0或1值,那麼你也可以使用stat_summarymean_cl_boot得到一個自舉95%的置信區間的百分比中止。下面是用假數據的示例:

library(scales) 

set.seed(389) 
sab2 = data.frame(locality=rep(1:6,each=100), aborted=sample(0:1, 600, replace=TRUE)) 

ggplot(sab2, aes(factor(locality), aborted)) + 
    stat_summary(fun.y=mean, geom="bar", fill="grey70") + 
    stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.2) + 
    scale_y_continuous(labels=percent_format(), limits=c(0,1)) + 
    theme_bw() 

enter image description here

點可能比barplot這裏更好:

ggplot(sab2, aes(factor(locality), aborted)) + 
    stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.2) + 
    stat_summary(fun.y=mean, geom="point", shape=21, fill="red", size=2) + 
    scale_y_continuous(labels=percent_format(), limits=c(0,1)) + 
    theme_bw() 

enter image description here

或者使用百分比值作爲點標記:

ggplot(sab2, aes(factor(locality), aborted)) + 
    stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.2, colour="grey60") + 
    stat_summary(fun.y=mean, geom="text", size=3, colour="red", 
       aes(label=paste0(sprintf("%1.1f", ..y..*100),"%"))) + 
    scale_y_continuous(labels=percent_format(), limits=c(0,1)) + 
    theme_bw() 

enter image description here

+0

非常感謝。您的假數據集可以工作,但不是我的。錯誤消息是:「錯誤:提供給連續縮放的離散值」。這是我的數據集的結構:data.frame':\t 1680 obs。 6個變量: $ year:因子w/2級別「2013」​​,「2014」:1 1 ... $ locality:Ord.factor w/6 levels「A」<「B」<..:5 5 ... $ plot:因子w/98等級「CM1」,「CM10」,「CM11」,..:1 ... $ seeds:int 3 0 4 6 2 5 6 1 5 5 ... $ aborted:因子w/2等級「0」,「1」:2 1 2 2 2 2 2 2 2 2 ... – Elena

+0

看起來像是因爲'aborted'是一個因素。它需要是數值或整數與值0或1,以獲得百分比由我的答案中的方法繪製。這就是「連續量程誤差的離散值」意味着什麼。您正在運行'scale_y_continuous',但您的y值是一個分類(即因子)變量)。 – eipi10

+0

非常感謝!現在我可以努力解決我的問題,歡呼! – Elena