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

如何在Plotly Express绘制的箱线图中添加均值(不使用Graph Objects)

不用Graph Objects给Plotly Express箱线图添加均值的方法

可以完全基于Plotly Express实现,不需要用到go.Box(),有两种常用方案:

方案1:直接启用boxmean参数显示均值线

Plotly Express的px.box()自带boxmean参数,设置为True即可在箱线图内显示均值线,支持facet_col分面场景,是最简单的实现方式:

import plotly.express as px
fig = px.box(device_field_strength_impact_df, 
        y='value',
        x='device_field_strength', 
        color='variable', 
        boxmean=True,  # 启用均值线显示
        facet_col='group',
        )
fig.show()

如果需要同时显示均值和标准差,可将boxmean设为"sd"。

方案2:叠加散点图显示均值点

如果希望用标记点突出显示均值位置,可先计算分组均值,再用px.scatter()绘制均值点并叠加到箱线图上:

步骤1:计算各分组的均值

按device_field_strength、variable、group分组计算value的均值:

mean_df = device_field_strength_impact_df.groupby(
    ['device_field_strength', 'variable', 'group']
)['value'].mean().reset_index()

步骤2:绘制箱线图并叠加均值点

import plotly.express as px

# 绘制基础箱线图
fig = px.box(device_field_strength_impact_df, 
        y='value',
        x='device_field_strength', 
        color='variable', 
        facet_col='group',
        )

# 绘制均值点散点图并叠加到箱线图
scatter_fig = px.scatter(mean_df, 
                         x='device_field_strength', 
                         y='value', 
                         color='variable', 
                         facet_col='group',
                         marker=dict(size=8, line=dict(width=1, color='black'))  # 设置点的样式
                         )
fig.add_traces(scatter_fig.data)

fig.show()

这种方式保留了Plotly Express自动处理图例、X轴标签和分面布局的优势,不会出现你之前用Graph Objects时遇到的标签和图例问题。


内容的提问来源于stack exchange,提问作者arthur.sw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:55:10