没有blitting
如果你不愿意使用blitting,解决方案是设置
RectangleSelector
的补丁可见(
RS.to_draw.set_visible(True)
)并将其范围设置为您想要的数据(
RS.extents = (0,4,0,1)
).
from __future__ import print_function
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
def line_select_callback(eclick, erelease):
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))
fig, current_ax = plt.subplots()
N = 100000
x = np.linspace(0.0, 10.0, N)
plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something
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)
# drawtype is 'box' or 'line' or 'none'
RS = RectangleSelector(current_ax, line_select_callback,
drawtype='box', useblit=False,
button=[1, 3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
interactive=True)
RS.to_draw.set_visible(True)
fig.canvas.draw()
RS.extents = (0,4,0,1)
plt.show()
带blitting
不幸的是,当使用blitting时,上述方法不起作用。
使用blitting的解决方案需要复制背景,然后将矩形设置为可见,但将
animated
属性设置为false。然后第一次绘制画布,显示矩形。但是,为了以后使用,我们需要设置
有生气的
属性再次设置为True。因此,首次在图形内部发生单击时,我们需要设置
有生气的
属性设置为True,并使用显示矩形之前已保存的背景对画布进行blit。
from __future__ import print_function
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
def line_select_callback(eclick, erelease):
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))
fig, current_ax = plt.subplots()
N = 100000
x = np.linspace(0.0, 10.0, N)
plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something
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)
# drawtype is 'box' or 'line' or 'none'
RS = RectangleSelector(current_ax, line_select_callback,
drawtype='box', useblit=True,
button=[1, 3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
interactive=True)
fig.canvas.draw()
bg = fig.canvas.copy_from_bbox(RS.ax.bbox)
RS.set_visible(True)
ext = (0,4,0,1)
RS.draw_shape(ext)
# Update displayed handles
RS._corner_handles.set_data(*RS.corners)
RS._edge_handles.set_data(*RS.edge_centers)
RS._center_handle.set_data(*RS.center)
for artist in RS.artists:
RS.ax.draw_artist(artist)
artist.set_animated(False)
fig.canvas.draw()
def initclick(evt):
RS.background = bg
RS.update()
for artist in RS.artists:
artist.set_animated(True)
fig.canvas.mpl_disconnect(cid)
cid = fig.canvas.mpl_connect("button_press_event",initclick)
plt.show()