1 回答

TA貢獻1886條經(jīng)驗 獲得超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)
請注意,如果調(diào)整圖形大小,這將不起作用,您需要copy_from_bbox在調(diào)整大小偵聽器中重新運行該行。
添加回答
舉報