我正在尝试在多绘图图中手动设置一个(共享)y 轴的范围,但由于某种原因,它也会影响其他 y 轴的范围。
看一下这个例子。我将首先创建一个 3x2 图形,每行共享一个 y 轴。
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.io as pio
pio.renderers.default = "browser"
np.random.seed(42)
N = 20
nrows, ncols, ntraces = 3, 2, 3
fig = make_subplots(
rows=nrows, cols=ncols,
shared_xaxes=True, shared_yaxes=True,
)
for r in range(nrows):
scale = 1 / 10 ** r
for c in range(ncols):
for t in range(ntraces):
y = np.random.randn(N) * scale
fig.add_trace(
row=r + 1, col=c + 1,
trace=go.Scatter(y=y, mode="markers+lines", name=f"trace {t}")
)
fig.update_layout(showlegend=False)
fig.show()
现在我只想手动设置第一行的范围,所以我这样做:
fig.update_yaxes(range=[-2, 2], row=1, col=1)
fig.show()
这确实根据需要设置了范围。问题是,这也会扰乱所有其他轴,将它们的范围更改为某个自动值(
[-1, 4]
):
我尝试使用
range
和 rangemode='normal'
的各种组合手动设置其他行的范围,例如:
fig.update_yaxes(range=[None, None], row=2, col=1)
fig.update_yaxes(range=None, row=2, col=1)
fig.update_yaxes(rangemode='normal', row=2, col=1)
似乎没有什么作用...
如何仅手动设置其中一个轴的 y 轴范围?
它看起来像一个错误,可能是由同时具有
shared_xaxes=True
和 shared_yaxes=True
引起的。
我认为你不能只更新一个 y 轴(因为它们是共享的),但你仍然可以更新一对 y 轴(在同一行)并为那些不应该更新其范围的轴设置
autorange=True
:
fig.update_yaxes(range=[-2, 2], row=1) # 'y' and 'y2'
fig.update_yaxes(autorange=True, row=2) # 'y3' and 'y4'
fig.update_yaxes(autorange=True, row=3) # 'y5' and 'y6'
您还可以通过指定任意对的轴 ID 在一次调用中完成此操作:
fig.update_layout(
yaxis_range=[-2, 2], # 'y' and 'y2'
yaxis3_autorange=True, # 'y3' and 'y4'
yaxis5_autorange=True, # 'y5' and 'y6'
)