【问题标题】:updating colorbar without resetting zoom history in matplotlib user interface在 matplotlib 用户界面中更新颜色条而不重置缩放历史记录
【发布时间】:2016-05-21 04:23:54
【问题描述】:

我正在尝试使用类似于例如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()

【问题讨论】:

    标签: python image matplotlib plot matplotlib-widget


    【解决方案1】:

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

    这里的问题是图形fig 的查看历史记录存储在两个cbook.Stack 对象(fig.canvas.toolbar._views 和fig.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。

    【讨论】:

    • 很好的答案和很好的洞察力,我自己永远无法解决这个问题。我使用了第一个解决方案,效果很好。虽然看起来有点破解,但我希望未来的更新不会破坏代码。谢谢!
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2017-11-10
    • 2015-02-05
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多