matplotlib链接的x轴和缩放时自动缩放的y轴

2024-05-16 13:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用链接(共享)的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

我错过什么了吗?


Tags: importaddtrue绘图plotmatplotlib堆栈链接
1条回答
网友
1楼 · 发布于 2024-05-16 13:39:15

在研究了matplotlib的axes.py的血淋淋的细节之后,似乎没有基于数据视图自动缩放轴的规定,因此没有高层次的方法来实现我想要的。

但是,也有“xlim_changed”事件,可以附加回调:

import numpy as np

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()
            # 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))

        # TODO: update limits from Patches, Texts, Collections, ...

        # 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

for ax in fig.axes:
    ax.callbacks.connect('xlim_changed', on_xlim_changed)

不幸的是,这是一个非常低级的黑客,它很容易被破解(除了线、反向或日志轴之外的其他对象…)

似乎无法钩住axes.py中的高级功能,因为高级方法不会将emit=False参数转发到set_xlim(),这是避免在set_xlim()和'xlim_changed'回调之间进入无限循环所必需的。

此外,似乎没有统一的方法来确定水平裁剪对象的垂直范围,因此在axes.py中有单独的代码来处理行、修补程序、集合等,这些都需要在回调中复制。

无论如何,上面的代码对我有效,因为我的绘图中只有行,而且我对tight=True布局很满意。似乎只要对axes.py进行一些更改,就可以更优雅地容纳此功能。

编辑:

我错了,我没能连接到更高级的自动缩放功能。它只需要一组特定的命令来正确地分离x和y。我更新了代码以在y中使用高级自动缩放,这将使它更加健壮。特别是,tight=False现在可以工作了(毕竟看起来好多了),而且反向/对数轴不应该是个问题。

剩下的一个问题是确定各种对象的数据限制,一旦裁剪到特定的x范围。这个功能应该是内置的matplotlib,因为它可能需要渲染器(例如,如果一个放大到屏幕上只剩下0或1个点,上面的代码就会中断)。Axes.relim()方法看起来是一个很好的候选者。如果数据已更改,它应该重新计算数据限制,但目前只处理行和修补程序。Axes.relim()可以有可选参数,用于指定x或y中的窗口

相关问题 更多 >