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

如何在Plotly柱状图中为每个柱子添加对应平均值的水平线?

给Plotly柱状图每个柱子添加对应平均值的水平线

要实现这个需求,你可以通过Plotly的add_shape方法,针对每个柱子的宽度范围绘制水平线,具体实现如下:

完整修改代码

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

def create_bar_chart(_dict, mean_scores, _title, _title_text, titles, image_paths):
    df = pd.DataFrame(dict(score=_dict.values(), trait=_dict.keys()))
    # 将平均值数据合并到DataFrame,方便后续遍历
    df['mean_score'] = df['trait'].map(mean_scores)
    _image = f"{_title_text}_sm.jpg"
    _width=600
    _height=400

    _fig = px.bar(df, x="trait", y="score")
    _fig.update_layout(xaxis_title=None, width=_width, height=_height)

    # 给每个柱子添加平均值水平线
    bar_width = 0.8  # Plotly默认柱状图宽度,可按需调整
    for idx, row in df.iterrows():
        x_center = idx  # 每个分类对应的x轴数值坐标
        x_left = x_center - bar_width / 2
        x_right = x_center + bar_width / 2
        mean_val = row['mean_score']
        # 添加水平线形状
        _fig.add_shape(
            type="line",
            x0=x_left,
            x1=x_right,
            y0=mean_val,
            y1=mean_val,
            line=dict(
                color="red",
                width=2,
                dash="dash"  # 可选:用虚线区分柱子和平均值线
            )
        )
    return _fig

# 示例调用
if __name__ == "__main__":
    trait_scores = {"分析思维": 0.5, "沟通能力": 0.6, "团队协作": 0.3}
    trait_means = {"分析思维": 0.4, "沟通能力": 0.35, "团队协作": 0.45}
    fig = create_bar_chart(trait_scores, trait_means, "能力评分", "ability_scores", [], [])
    fig.show()

关键说明

  1. 参数新增:函数新增mean_scores参数,这是一个和trait分类一一对应的字典,存储每个类别的平均值。
  2. 柱子边界计算:Plotly默认柱状图宽度为0.8,每个分类在x轴上的数值坐标从0开始递增,据此计算出每个柱子的左右边界,确保水平线宽度和柱子完全匹配。
  3. 样式调整:可以通过修改line参数调整水平线的颜色、粗细、线型,比如把dash改为solid切换为实线,或者更换color为其他配色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:32:55