在鼠标聚焦时刷新matplotlib图表
我正在使用matplotlib,并开启了交互模式。在进行一些计算,比如说优化过程时,这个过程有很多步骤,我会在每一步都画出中间结果来调试。这些图表往往会占满整个屏幕,并且重叠得很厉害。
我遇到的问题是,在计算过程中,那些部分被遮挡或者完全被遮住的图表,在我点击它们的时候不会刷新,显示的只是一个空白的灰色区域。
我希望在点击图表时,如果有必要的话,强制它重新绘制,否则显示这些图表就没有意义。目前,我在代码里插入了pdb.set_trace(),这样我可以暂停程序,点击所有图表来查看发生了什么。
有没有办法让matplotlib在图表获得鼠标焦点或者被调整大小时,强制它重新绘制,即使它正在忙着做其他事情?
2 个回答
0
你有没有试过在绘图之前先调用 plt.figure(fig.number)
,然后在绘图完成后再调用 plt.show()
?这样做应该能更新所有的图形。
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 - 当鼠标进入一个新的图形时
想了解更多,可以点击 这里: