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

Plotly中update_layout设置副Y轴范围[0, None]不生效问题

解决Plotly副Y轴起始值无法设为0的问题

当你用make_subplots(specs=[[{"secondary_y": True}]])创建双Y轴图表时,直接在update_layout里设置yaxis2的range会被Plotly自动生成的轴配置覆盖,导致设置不生效。

解决方案

改用update_yaxes方法,通过secondary_y=True指定要修改的是副Y轴,再设置范围参数即可生效。

修改后的完整代码

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(go.Bar(
    x=smy[smy['variable'] == 'Weekly_Sales_sum']['Year'],
    y=smy[smy['variable'] == 'Weekly_Sales_sum']['value'],
    name='Weekly Sales Sum'
))

fig.add_trace(go.Scatter(
    x=smy[smy['variable'] == 'Weekly_Sales_size']['Year'],
    y=smy[smy['variable'] == 'Weekly_Sales_size']['value'],
    name='Weekly Sales Size',
    yaxis='y2'
))

# 统一配置主副Y轴
fig.update_yaxes(title_text='Weekly Sales Sum', secondary_y=False)
fig.update_yaxes(title_text='Weekly Sales Size', secondary_y=True, range=[0, None])

fig.update_layout(title='Bar and Line Chart for Weekly Sales Sum and Size')

pyo.iplot(fig)

补充说明

  • 如果需要自定义副Y轴的最大值,把None换成具体数值即可,比如range=[0, 1500]
  • 主Y轴的配置也可以通过secondary_y=False在update_yaxes里统一设置,代码结构更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:52:15