1 回答
TA贡献1886条经验 获得超2个赞
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
plt.ion()
rng = np.random.default_rng()
def make_vline(event):
fig.canvas.restore_region(fig.my_bg)
ax = event.inaxes
if getattr(ax, 'my_vline', None) is None:
ax.my_vline = ax.axvline(event.xdata, linewidth=4, color='r', zorder=3)
else:
ax.my_vline.set_xdata(event.xdata)
ax.draw_artist(ax.my_vline)
ax.figure.canvas.blit()
ax.figure.canvas.flush_events()
def add_line_collection(ax):
n_chans = 400
n_times = 10001
xs = np.linspace(0, 10, n_times)
ys = rng.normal(size=(n_chans, n_times)) * 1e-6
segments = [np.vstack((xs, ys[n])).T for n in range(n_chans)]
yoffsets = np.arange(n_chans)
offsets = np.vstack((np.zeros_like(yoffsets), yoffsets)).T
lc = LineCollection(segments, offsets=offsets, linewidths=0.5, colors='k')
ax.add_collection(lc)
ax.set_xlim(xs[0], xs[-1])
ax.set_ylim(yoffsets[0] - 0.5, yoffsets[-1] + 0.5)
ax.set_yticks(yoffsets)
fig, ax = plt.subplots()
add_line_collection(ax)
callback_id = fig.canvas.mpl_connect('button_press_event', make_vline)
plt.pause(0.1)
fig.my_bg = fig.canvas.copy_from_bbox(fig.bbox)
请注意,如果调整图形大小,这将不起作用,您需要copy_from_bbox在调整大小侦听器中重新运行该行。
添加回答
举报