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

Plotly add_hline()函数未正确绘制balance列均值水平线

Plotly调用add_hline()添加水平参考线始终显示在y=0位置解决方法

问题表现

  • 基于DataFrame的balance列计算得到均值mean_balance,单独打印验证数值准确
  • 调用add_hline(y=mean_balance)添加水平参考线时,线条始终被绘制在y=0刻度位置
  • 不通过add_hline()实现参考线添加时,显示效果正常

问题复现代码

ed_s = px.histogram(
       data_frame=df,
       x = 'age',
       y = 'balance',
       color='y',
       labels={'age':"Age", "balance":"Balance"},
       title=format_title("Age and Balance", "Also whether the customer subed to a term deposit or not"),
       template=custom_template)

fig = go.Figure(data=ed_s)
fig.add_hline(y=mean_balance, line_dash='dash', line_color="firebrick")
iplot(fig)

问题原因

核心问题是重建画布时丢失了坐标轴配置:
px.histogram()在同时传入x、y参数时会默认做分箱聚合,生成的figure对象自带和聚合逻辑匹配的y轴映射、范围配置。代码中仅将px生成对象的data属性传入go.Figure()重建画布,没有同步传入原布局配置,导致add_hline()使用的默认y轴坐标系和图表trace实际绑定的坐标系不匹配,传入的y值被错误解析,最终线条落在y=0位置。

修复方案

二选一即可:

  • 直接在px.histogram()生成的figure对象上调用add_hline(),不需要额外重建go.Figure对象,修改后代码如下:
ed_s = px.histogram(
       data_frame=df,
       x = 'age',
       y = 'balance',
       color='y',
       labels={'age':"Age", "balance":"Balance"},
       title=format_title("Age and Balance", "Also whether the customer subed to a term deposit or not"),
       template=custom_template)

ed_s.add_hline(y=mean_balance, line_dash='dash', line_color="firebrick")
iplot(ed_s)
  • 如果必须重建go.Figure对象,需要将原px生成对象的layout属性同步传入,保证坐标轴配置完整:
ed_s = px.histogram(
       data_frame=df,
       x = 'age',
       y = 'balance',
       color='y',
       labels={'age':"Age", "balance":"Balance"},
       title=format_title("Age and Balance", "Also whether the customer subed to a term deposit or not"),
       template=custom_template)

fig = go.Figure(data=ed_s.data, layout=ed_s.layout)
fig.add_hline(y=mean_balance, line_dash='dash', line_color="firebrick")
iplot(fig)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:39:18