[英]How to plot binomial variable percentage bar plot with ggplot2
我正在繪制以下腳本中名為“aborted”的二項式變量(0/1):
`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))`
這就是結果:
如果我想僅繪制中止的百分比(“中止”因子的“0”級別),我可以在代碼中更改什么? 我可以獲得類似於以下的情節(但有中止的百分比):
謝謝!
使用stat_summary
計算的平均值aborted
,這僅僅是個中止時aborted
呈現的0或1值,那么你也可以使用stat_summary
與mean_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()
點數可能比這里的條形圖更好:
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()
或使用百分比值作為點標記:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.