Skip to content

Instantly share code, notes, and snippets.

@larsoner
Created February 25, 2021 14:01
Show Gist options
  • Save larsoner/b6e7b274b79adede13c7b6defa9d1c79 to your computer and use it in GitHub Desktop.
Save larsoner/b6e7b274b79adede13c7b6defa9d1c79 to your computer and use it in GitHub Desktop.
Try to get speedups with mpl by using blitting, linecollection, single line, etc.
import time
import mne
import numpy as np
import matplotlib.pyplot as plt
raw = mne.io.read_raw_fif(
mne.datasets.sample.data_path() + '/MEG/sample/sample_audvis_raw.fif')
data, times = raw[:, :]
n_points = 1000
norms = np.std(data, axis=-1, keepdims=True)
data -= np.mean(data, axis=1, keepdims=True)
norms[norms == 0] = 1
data /= norms
data += np.arange(len(data))[:, np.newaxis]
fig, ax = plt.subplots(figsize=(8, 6), dpi=100)
x = times[:n_points]
ys = data[:, :n_points]
# Collection (same speed)
# from matplotlib.collections import LineCollection
# line_segments = LineCollection([np.column_stack([x, y]) for y in ys])
# line_segments.set_array(x)
# ax.add_collection(line_segments)
# Plot
def _nan_ravel(x, ys):
x = np.tile(np.pad(
x, (0, 1), 'constant', constant_values=np.nan), ys.shape[0])
ys = np.pad(
ys, ((0, 0), (0, 1)), 'constant', constant_values=np.nan).ravel()
return x, ys
x, ys = _nan_ravel(x, ys)
h = ax.plot(x, ys.T, color='k', lw=0.5, alpha=0.5, antialiased=True)[0]
ax.set(xlim=times[[0, n_points - 1]], ylim=[-0.5, len(data) + 0.5])
class Updater():
def __init__(self):
self.offset = 0
def __call__(self):
sl = slice(self.offset, self.offset + n_points)
t = times[sl]
x, ys = _nan_ravel(times[sl], data[:, sl])
h.set_xdata(x)
h.set_ydata(ys.T)
self.offset += 10
if self.offset > len(times) - n_points:
self.offset = 0
ax.set(xlim=t[[0, -2]])
fig.canvas.draw_idle()
t0 = time.time()
fig.canvas.flush_events()
print(time.time() - t0)
up = Updater()
timer = fig.canvas.new_timer(interval=int(round(1000 / 60)))
fig.canvas.mpl_connect('close_event', lambda ev: timer.stop())
timer.add_callback(up)
timer.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment