ggstatsplot::ggbarstats
library(ggstatsplot)
df$活产 <- relevel(factor(df$活产,ordered = F) ,ref = "1") #ref 修改因子变量参照水平
df %>% ggstatsplot::ggbarstats(活产,分组变量,
bar.proptest = F, #不显示p值的显著与否
palette = 'Set3', #设置颜色板
results.subtitle = F #副标题不显示统计结果)
#+coord_flip() #旋转坐标轴
ggplot2::geom_bar
library(ggplot2)
library(scales)
library(dplyr)
prop_data <- df %>%
group_by(分组) %>%
summarise(prop_value = mean(活产 == 1),count = n())
ggplot(prop_data, aes(x = 分组, y = prop_value, fill = 分组)) +
geom_bar(stat = "identity", position = position_stack(reverse = F)) +
# 在条形图上显示比例值
geom_text( aes(label = paste0(scales::percent(prop_value,accuracy = 0.01), "\n", "n=", count)), #accuracy 小数位
position = position_stack(reverse = F), vjust = 1) +
# 调整 y 轴标签为百分比
scale_y_continuous(limits = c(0, 0.75), labels = scales::percent) + #limits y轴区间
labs(title = "活产率", x = "分组", y = "") + #labs
theme_bw()+
scale_fill_manual(values = rep("steelblue1",time=10)) #values填充颜色