如何创建具有链接(共享)x轴的绘图堆栈,这些x轴在缩放期间自动缩放所有“从属”绘图的y轴?例如:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.plot([0,1])
ax2.plot([2,1])
plt.show()
当我放大ax1时,这也会更新ax2的x轴(到目前为止还不错),但我也希望ax2的y轴根据现在可见的数据范围自动缩放。所有自动缩放设置都处于启用状态(默认设置)。创建ax2后手动设置自动缩放设置无济于事:
ax2.autoscale(enable=True, axis='y', tight=True)
ax2.autoscale_view(tight=True, scalex=False, scaley=True)
print ax2.get_autoscaley_on()
-> True
我错过了什么吗?
发布于 2020-06-13 05:44:56
我不知道适用于此的协议,但我最近使用此答案对一些具有一些fill_betweens的时间序列数据进行了重新缩放。下面是我为实现这一点所做的更改。我打赌8年后会有更简单的方法来做这件事……
def on_xlim_changed(ax):
xlim = ax.get_xlim()
for a in ax.figure.axes:
# shortcuts: last avoids n**2 behavior when each axis fires event
if a is ax or len(a.lines) == 0 or getattr(a, 'xlim', None) == xlim:
continue
ylim = np.inf, -np.inf
for l in a.lines:
x, y = l.get_data()
if np.issubdtype(x.dtype, np.datetime64):
# convert dates to numbers so searchsorted works
x = matplotlib.dates.date2num(x)
# faster, but assumes that x is sorted
start, stop = np.searchsorted(x, xlim)
yc = y[max(start-1,0):(stop+1)]
ylim = min(ylim[0], np.nanmin(yc)), max(ylim[1], np.nanmax(yc))
for c in a.collections:
for p in c.get_paths():
vertices = p.vertices
x, y = vertices[:, 0], vertices[:, 1]
# x won't be sorted when you pull path vertices
yc = y[(x >= xlim[0]) & (x <= xlim[1])]
ylim = min(ylim[0], np.nanmin(yc)), max(ylim[1], np.nanmax(yc))
# TODO: update limits from Patches, Texts, ...
# x axis: emit=False avoids infinite loop
a.set_xlim(xlim, emit=False)
# y axis: set dataLim, make sure that autoscale in 'y' is on
corners = (xlim[0], ylim[0]), (xlim[1], ylim[1])
a.dataLim.update_from_data_xy(corners, ignore=True, updatex=False)
a.autoscale(enable=True, axis='y')
# cache xlim to mark 'a' as treated
a.xlim = xlim
https://stackoverflow.com/questions/11086724
复制相似问题