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

如何在共享X轴的Dash子图中强制缩放窗口为正方形?

解决共享X轴子图的正方形缩放问题

要实现共享X轴的子图拖拽缩放时强制为正方形,需为每个Y轴设置与X轴绑定的缩放比例,同时确保X轴缩放行为一致。以下是修改后的代码:

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=2, cols=1, shared_xaxes=True)

fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
    row=1, col=1
)

fig.add_trace(
    go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
    row=2, col=1
)

# 核心设置:绑定Y轴与X轴缩放比例,强制正方形
fig.update_yaxes(
    scaleanchor='x',
    scaleratio=1,
    row=1, col=1
)
fig.update_yaxes(
    scaleanchor='x',
    scaleratio=1,
    row=2, col=1
)

# 确保共享X轴缩放同步
fig.update_xaxes(matches='x')

fig.update_layout(
    height=600,
    width=800,
    title_text="共享X轴的正方形缩放子图",
    dragmode='select'  # 明确使用矩形选择缩放模式
)

fig.show()

关键说明

  • scaleanchor='x':将Y轴缩放锚定到对应X轴,保证X、Y缩放行为关联。
  • scaleratio=1:设置X与Y的缩放范围长度比例为1,拖拽时自然形成正方形选择框。
  • update_xaxes(matches='x'):维持共享X轴的缩放同步性,避免子图X轴缩放不一致。

若用于Dash应用,直接将上述fig传入dcc.Graph组件即可实现相同效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:31:23