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

如何在Julia的StatsPlots箱线图中添加均值点?

在Julia的StatsPlots中为箱线图添加均值点

在StatsPlots里,你可以用带感叹号的scatter!()函数实现类似R中points()的功能——它能在已绘制的箱线图上叠加均值点,这是Julia绘图库的惯例:带!的函数会修改当前的绘图对象。

单组数据的实现

先修正你原代码中数据长度不匹配的问题,再完成完整流程:

using StatsPlots

# 生成匹配长度的数据
group = repeat(['A'], outer=300)
data = randn(300)

# 先绘制箱线图并保存绘图对象
p = boxplot(group, data)

# 计算数据均值
mean_val = mean(data)

# 叠加红色均值点:单组箱线图的x轴位置对应1
scatter!(p, [1], [mean_val], color=:red, markersize=6, label="均值")

# 显示图像
display(p)

多组数据的实现

如果是多分类的箱线图,只需循环计算每组均值,再对应每组的x轴位置添加点:

using StatsPlots

# 生成多组数据
groups = repeat(['A', 'B', 'C'], outer=100)
data = vcat(randn(100), randn(100) .+ 1, randn(100) .- 1)

# 绘制多组箱线图
p = boxplot(groups, data)

# 计算每组的均值
group_means = [mean(data[groups .== g]) for g in unique(groups)]

# 对应每组的x位置(1、2、3)添加均值点
scatter!(p, 1:length(group_means), group_means, color=:red, markersize=6, label="均值")

display(p)

关键说明

  • scatter!()是核心:它和R的points()作用一致,用于在已有图形上叠加散点
  • x轴位置对应:单组箱线图的x位置是1,多组时按类别顺序依次为1、2、3...
  • 可自定义样式:通过markersize(点大小)、marker(点形状)、color(颜色)等参数调整均值点外观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:00:23