You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中绘制带置信区间(CI)的单因素方差分析(One-way ANOVA)图?

实现带置信区间的单因素方差分析可视化

嘿,我完全懂你想要的那种专业的带置信区间的方差分析图效果!咱们先从你的现有代码出发,一步步调整到目标样式~

首先,先回顾你的数据集定义和初始绘图代码:

你的原始数据集代码

mydat=structure(list(Price = c(1480000L, 1480000L, 1035000L, 1480000L, 1465000L, 689000L, 611000L, 611000L, NA, 855000L, 855000L, NA, 1480000L, 1035000L, NA, 1465000L, 850000L), Regionname = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L ), .Label = c("Eastern Victoria", "Northern Metropolitan"), class = "factor")), .Names = c("Price", "Regionname"), class = "data.frame", row.names = c(NA, -17L))

你的初始箱线图代码

require(ggplot2) 
ggplot(mydat, aes(x = Regionname, y = Price)) + 
  geom_boxplot(fill = "grey80", colour = "blue") + 
  scale_x_discrete() + 
  xlab("Regionname") + 
  ylab("Price")

调整方案:添加均值与95%置信区间

目标图的核心是展示每组的均值点和95%置信区间(CI),我们可以用ggplot2的stat_summary()函数自动计算并绘制,同时可以保留箱线图展示数据分布,也可以只保留均值+CI的组合。

方案1:箱线图 + 均值+CI(推荐,同时展示分布和统计量)

首先清理数据中的缺失值(避免绘图报错),然后添加统计元素:

require(ggplot2)

# 清理缺失值
mydat_clean <- na.omit(mydat)

# 绘制带均值和置信区间的箱线图
ggplot(mydat_clean, aes(x = Regionname, y = Price)) +
  # 基础箱线图,保留你的原始样式
  geom_boxplot(fill = "grey80", colour = "blue", alpha = 0.5) +
  # 添加均值点(红色实心菱形,更醒目)
  stat_summary(fun = mean, geom = "point", shape = 18, size = 4, color = "red") +
  # 添加95%置信区间误差棒
  stat_summary(fun.data = mean_cl_normal, geom = "errorbar", width = 0.2, color = "red") +
  # 优化标签和主题,贴近目标样式
  labs(x = "Region Name", y = "Price") +
  theme_bw() +
  theme(axis.title = element_text(size = 12, face = "bold"),
        axis.text = element_text(size = 10))

方案2:仅展示均值+CI(纯统计量展示)

如果不需要箱线图,只保留均值和置信区间,去掉geom_boxplot()即可:

ggplot(mydat_clean, aes(x = Regionname, y = Price)) +
  stat_summary(fun = mean, geom = "point", shape = 18, size = 4, color = "red") +
  stat_summary(fun.data = mean_cl_normal, geom = "errorbar", width = 0.2, color = "red") +
  labs(x = "Region Name", y = "Price") +
  theme_bw() +
  theme(axis.title = element_text(size = 12, face = "bold"),
        axis.text = element_text(size = 10))

方案3:用ggpubr快速生成学术风格图表

如果你想要更快捷的方式,可以用ggpubr包,它专门针对学术绘图优化,一行代码就能生成目标样式:

# 先安装包(首次使用时)
# install.packages("ggpubr")
library(ggpubr)

ggboxplot(mydat_clean, x = "Regionname", y = "Price",
          fill = "grey80", color = "blue",
          add = "mean_ci",  # 自动添加均值和95%置信区间
          add.params = list(color = "red", size = 1)) +
  labs(x = "Region Name", y = "Price") +
  theme_bw()

内容的提问来源于stack exchange,提问作者psysky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:14:11