可以使用ggplot2包中的geom_bar()和stat_summary()函数来绘制带95%置信区间的柱状图。以下是一个示例代码:

library(ggplot2)
library(dplyr)

# 创建一个示例数据集
set.seed(123)
df <- data.frame(group = rep(c("A", "B", "C"), each = 10),
                 value = rnorm(30, mean = c(5, 8, 12), sd = c(1, 2, 3)))

# 计算每个组的平均值和95%置信区间
ci <- df %>% group_by(group) %>% 
  summarize(mean = mean(value), 
            lower = mean - qt(0.025, df = n() - 1) * sd(value) / sqrt(n()), 
            upper = mean + qt(0.025, df = n() - 1) * sd(value) / sqrt(n()))

# 绘制柱状图和置信区间
ggplot(df, aes(x = group, y = value)) +
  geom_bar(stat = "summary", fun = "mean", fill = "blue", 
           color = "black", size = 0.5) +
  geom_errorbar(aes(ymin = ci$lower, ymax = ci$upper), 
                width = 0.4, size = 0.8, color = "black") +
  labs(title = "柱状图带95%置信区间",
       x = "组别",
       y = "数值") +
  theme_classic()

运行代码后,将会生成一个带95%置信区间的柱状图。其中,每个柱子的高度表示该组的平均值,黑色的线条表示95%置信区间。可以根据需要修改图例、颜色等参数

在R中绘制带95置信区间的柱状图

原文地址: https://www.cveoy.top/t/topic/cZnJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录