gpt4 book ai didi

python - 在 matplotlib 用户界面中更新颜色条而不重置缩放历史记录

转载 作者:行者123 更新时间:2023-11-28 18:32:46 26 4
gpt4 key购买 nike

我正在尝试制作一个绘图,其中使用类似于例如的方案在可视化数据的基础上缩放更新色标。 http://matplotlib.org/examples/event_handling/viewlims.html (还要注意类似的问题 Matplotlib imshow, dynamically resample based on zoom )

但是我在处理颜色条时遇到了一个问题,在删除它并添加一个新的之后,缩放历史被重置。在我的真实代码中,颜色条更新是在每次缩放时完成的,因此 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()

最佳答案

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

这里的问题是图形 fig 的 View 历史存储在两个 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()

对于 toolmanager,您需要查看 backend_tools 中的 ToolViewsPositions。

关于python - 在 matplotlib 用户界面中更新颜色条而不重置缩放历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35321613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com