簡體   English   中英

如何用ggplot2繪制二項式可變百分比條形圖

[英]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_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()

在此輸入圖像描述

點數可能比這里的條形圖更好:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM