4

我正在尝试使用类似于例如http://matplotlib.org/examples/event_handling/viewlims.html的方案,在可视化数据的基础上根据缩放更新色标(另请注意类似的问题)Matplotlib imshow,基于缩放动态重采样

但是我在处理颜色条时遇到了一个问题,在删除它并添加一个新的之后,缩放历史被重置。在我的真实代码中,每次缩放都会更新颜色条,因此 matplotlib 图中的返回和主页按钮根本不起作用。

看下面的示例代码可能会更清楚。是什么原因?有没有办法防止这种情况发生?

从所有不必要的部分中剥离的代码或多或少看起来像这样:

#create and plot a test image with colorbar,
#zoom and everything works
import numpy as np
N=100
a=np.random.random((N,N))
plt.figure()
plt.imshow(a,interpolation='none')
plt.colorbar()
plt.show()
#at this point I can zoom and use back and forward buttons as always

#but if I zoom in and then execute the following code, the history is reset and I cannot go back or home any more (the zooming history works in the future, but is reset every time I replace the colorbar):
ax=plt.gca()
im=ax.images[-1]
im.colorbar.remove()
#in real code, color range is updated here
plt.colorbar()
4

1 回答 1

1

不幸的是,这很困难,而且还取决于您使用的后端。有两种类型的工具栏:toolbar2,通常是默认的,toolmanager,将成为默认的。我的解决方案将基于当前默认的工具栏 2。

这里的问题是图形的查看历史记录fig存储在两个cbook.Stack对象 (fig.canvas.toolbar._viewsfig.canvas.toolbar._positions) 中,在更新期间由fig.canvas.toolbar.update(). 因此,我可以轻松想到两种解决方案。

首先是复制两个堆栈然后恢复它们:

import copy
s = copy.copy( fig.canvas.toolbar._views )
p = copy.copy( fig.canvas.toolbar._positions )
ax=plt.gca()
im=ax.images[-1]
im.colorbar.remove()
#in real code, color range is updated here
plt.colorbar()
fig.canvas.toolbar._views = s
fig.canvas.toolbar._positions = p

第二个是从您的NavigationToolbar2对象中删除更新功能。例如:

fig.canvas.toolbar.update = lambda: None

然后您的原始代码将在不重置历史记录的情况下工作:

ax=plt.gca()
im=ax.images[-1]
im.colorbar.remove()
#in real code, color range is updated here
plt.colorbar()

对于工具管理器,您需要查看 backend_tools 中的 ToolViewsPositions。

于 2016-02-11T10:47:44.463 回答