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

使用restyle更新Plotly图表时如何固定Y轴范围不随数据变动

问题原因

使用restyle方法更新折线数据时,Plotly会默认触发轴范围自动适配逻辑,覆盖预先设置的autorange=False和固定范围配置,导致Y轴范围随数据变动。

解决方法

你可以任选以下两种方案之一实现Y轴范围固定:

  • 方案1(推荐,不影响用户手动缩放Y轴):将按钮的更新方法改为update,每次更新数据的同时重新指定Y轴固定配置
  • 方案2(改动最小,完全锁定Y轴):给Y轴添加fixedrange=True属性,禁止任何场景下自动/手动修改Y轴范围

完整修改后代码(方案1实现)

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import datetime

np.random.seed(123)
df = pd.DataFrame(np.random.randint(-10, 12, size=(200, 4)),
                  columns=list('ABCD'))
datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),
                         periods=200).tolist()

df2 = df.copy()

df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df.iloc[0] = 0
df = df.cumsum()

df2['dates'] = datelist 
df2 = df2.set_index(['dates'])
df2.index = pd.to_datetime(df2.index)
df2.iloc[0] = 0
df2 = df2.cumsum()

# plotly
fig = go.Figure()
# set up ONE trace
fig.add_trace(go.Scatter(x=df.index,
                         y=df[df.columns[0]],
                         visible=True,
                         )
             )

buttons1 = []
buttons2 = []

fig.add_trace(go.Scatter(x=df2.index,
                         y=df2[df.columns[0]],
                         visible=True)
             )

# 第一个下拉菜单按钮配置,改用update方法
for col in df.columns:
    buttons1.append(dict(method='update',
                        label=col,
                        visible=True,
                        args=[
                            # 第一个参数:更新trace属性
                            {'y':[df[col]], 'x':[df.index], 'type':'scatter'}, 
                            # 第二个参数:更新layout属性,固定Y轴范围
                            {'yaxis': {'range': [-400, 400], 'autorange': False}}
                        ],
                        )
                  )

# 第二个下拉菜单按钮配置,改用update方法
for col in df2.columns:
    buttons2.append(dict(method='update',
                        label=col,
                        visible=True,
                        args=[
                            {'y':[df2[col]], 'x':[df2.index], 'type':'scatter'}, 
                            {'yaxis': {'range': [-400, 400], 'autorange': False}}
                        ],
                        )
                  )

# 调整下拉菜单配置
updatemenus = []
updatemenus.append(dict())
updatemenus[0]['buttons'] = buttons1
updatemenus[0]['direction'] = 'down'
updatemenus[0]['showactive'] = True
updatemenus[0]['y'] = 1.12

updatemenus.append(dict())
updatemenus[1]['buttons'] = buttons2
updatemenus[1]['direction'] = 'down'
updatemenus[1]['showactive'] = True
updatemenus[1]['y'] = 1

# 添加下拉菜单到图表
fig.update_layout(showlegend=False, updatemenus=updatemenus)
fig.update_yaxes(range=[-400, 400], autorange=False)

fig.show()
fig.write_html("./plot.html")

方案2快速实现

如果不需要保留用户手动缩放Y轴的能力,无需修改按钮配置,仅需要把原来的Y轴更新代码修改为如下内容即可:

fig.update_yaxes(range=[-400, 400], autorange=False, fixedrange=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 18:06:06