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
相关产品推荐
相关产品推荐

