添加回調draw_event
S:
def mycallback(event):
if RS.active:
RS.update()
plt.connect('draw_event', mycallback)
使縮放或平移後的RectangleSelector
堅持,並與useblit=True
兼容。
例如,使用code from the docs作爲基礎:
from __future__ import print_function
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
import threading
import datetime as DT
def line_select_callback(eclick, erelease):
'eclick and erelease are the press and release events'
x1, y1 = eclick.xdata, eclick.ydata
x2, y2 = erelease.xdata, erelease.ydata
print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
print(" The button you used were: %s %s" % (eclick.button, erelease.button))
def toggle_selector(event):
print(' Key pressed: {}'.format(event.key))
if event.key in ['D', 'd'] and RS.active:
print(' RectangleSelector deactivated.')
RS.set_active(False)
RS.set_visible(False)
RS.update()
if event.key in ['A', 'a'] and not RS.active:
print(' RectangleSelector activated.')
RS.set_active(True)
RS.set_visible(True)
RS.update()
def mycallback(event):
if RS.active:
# print('mycallback')
RS.update()
# def persist_rect(newlims):
# print('persist_rect')
# RS.set_visible(True)
# RS.update()
fig, ax = plt.subplots()
# figtype = type(fig)
# figtype._draw = figtype.draw
# def mydraw(self, renderer):
# print('figure.draw')
# self._draw(renderer)
# figtype.draw = mydraw
N = 100000
x = np.linspace(0.0, 10.0, N)
RS = RectangleSelector(ax, line_select_callback,
drawtype='box', useblit=True,
button=[1, 3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
interactive=True)
plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7)
plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5)
plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3)
plt.connect('key_press_event', toggle_selector)
plt.connect('draw_event', mycallback)
# ax.callbacks.connect('xlim_changed', persist_rect)
# ax.callbacks.connect('ylim_changed', persist_rect)
plt.show()
爲什麼mycallback
工作,但persist_rect
不?
如果取消註釋上面的註釋的語句,你會得到一些打印輸出將看起來就象這樣:
figure.draw
mycallback
figure.draw
mycallback
(4.09, -0.53) --> (8.15, 0.38)
The button you used were: 1 1
persist_rect
persist_rect
figure.draw
mycallback
Key pressed: q
注意persist_rect
被figure.draw
之前調用,而mycallback
是後來被稱爲。 figure.draw
不繪製RectangleSelection
,但它確實繪製了用於背景的Rectangle
。所以figure.draw
模糊RectangleSelection
。 因此persist_rect
暫時顯示RectangleSelection
,但它未能堅持。 mycallback
因爲在figure.draw
之後被調用。
你有沒有檢查這個問題的答案:https://stackoverflow.com/questions/34517484/persistent-rectangle-selector? –
@JafferWilson:感謝您指出這個問題。不幸的是,答案不起作用。按照原樣使用時,矩形將立即消失。如果與'interactive = True'一起使用,則與上述問題相同的問題仍然存在。 – ImportanceOfBeingErnest