如何使matplotlib图表在鼠标聚焦时刷新

6

我正在使用交互模式的matplotlib,进行计算,比如说一个有很多步骤的优化,在每一步绘制中间结果以进行调试。这些图表经常填满屏幕,并且在很大程度上重叠。

我的问题是,在计算期间,部分或全部遮挡的图形在我单击它们时不会刷新。它们只是一个空白的灰色。

如果需要,我希望能强制重新绘制图形,当我单击一个图形时,否则它对于显示没有用。目前,我在代码中插入pdb.set_trace(),以便我可以停止并单击所有图形,以查看发生了什么。

是否有一种方法可以强制matplotlib在获得鼠标焦点或被调整大小时重新绘制图形,即使它正在忙于做其他事情?

2个回答

1

这样的东西可能适合您:

import matplotlib.pyplot as plt
import numpy as np

plt.ion() # or leave this out and run with ipython --pylab

# draw sample data
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(np.random.rand(10))

class Refresher:
    # look for mouse clicks
    def __init__(self, fig):
        self.canvas = fig.canvas
        self.cid = fig.canvas.mpl_connect('button_press_event', self.onclick)

    # when there is a mouse click, redraw the graph
    def onclick(self, event):
        self.canvas.draw()

# remove sample data from graph and plot new data. Graph will still display original trace
line.remove()
ax.plot([1,10],[1,10])

# connect the figure of interest to the event handler 
refresher = Refresher(fig)
plt.show()

每当您单击图形时,它将重新绘制图形。

您还可以尝试其他事件处理方式,例如

  • ResizeEvent-图形画布被调整大小
  • LocationEvent-鼠标进入新图形

这里查看更多信息:


0
你尝试过在绘制图形之前调用plt.figure(fig.number),并在绘制图形后调用plt.show()吗?这应该会更新所有的图形。

不,我还没有尝试过使用plt.show()。看看它的使用文档(http://matplotlib.sourceforge.net/faq/howto_faq.html#use-show),似乎不会产生预期效果。 - Paul
@Paul 如果你使用了plt.ion(),那么show()应该会隐式地调用draw()。确保先运行plt.figure(fig.number),你的图形应该会自动更新。 - Chen Xing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接