2016-05-03 98 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