gpt4 book ai didi

r - 如何使用ggplot2绘制二项变量百分比条形图

转载 作者:行者123 更新时间:2023-12-04 09:15:07 40 4
gpt4 key购买 nike

我在以下脚本中绘制了一个名为“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))`    

结果是这样的:

enter image description here

如果我只想绘制中止百分比(“中止”因素的“0”水平),我可以在我的代码中更改什么?我可以获得类似于以下的图(但有 % 已中止):

enter image description here

谢谢!

最佳答案

使用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

这里的点可能比条形图更好:

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

关于r - 如何使用ggplot2绘制二项变量百分比条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37008524/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com