Skip to content

Instantly share code, notes, and snippets.

@afvincent
Created August 5, 2016 10:20
Show Gist options
  • Save afvincent/cfca2e58cc8d9f6f97103086e93e8815 to your computer and use it in GitHub Desktop.
Save afvincent/cfca2e58cc8d9f6f97103086e93e8815 to your computer and use it in GitHub Desktop.
Possible new version of the event handling resample.py
import numpy as np
import matplotlib.pyplot as plt
# A class that will downsample the data if there are too many points to display
class DataDisplayResampler(object):
def __init__(self, xdata, ydata, max_disp_samples=80):
self.origYData = ydata
self.origXData = xdata
self.max_disp_samples = max_disp_samples
self.delta = xdata[-1] - xdata[0]
def resample(self, xstart, xend):
mask = (self.origXData > xstart) & (self.origXData < xend)
xdata = self.origXData[mask]
ydata = self.origYData[mask]
downsampled = False # Convenience flag to set a responsive title
if len(xdata) > self.max_disp_samples:
# Very simple downsampling that takes the points within
# the range and picks every Nth point according to the
# downsampling ratio.
ds_ratio = len(xdata) // max(1, (self.max_disp_samples // 2))
xdata = xdata[::ds_ratio]
ydata = ydata[::ds_ratio]
downsampled = True
return xdata, ydata, downsampled
def update(self, ax):
# Update the line
lims = ax.viewLim
if np.abs(lims.width - self.delta) > 1e-8:
self.delta = lims.width
xx, yy, dsed = self.resample(*lims.intervalx)
self.line.set_data(xx, yy)
ax.set_title("Downsampled display" if dsed else "Full display")
ax.figure.canvas.draw_idle()
# Create a signal
xdata = np.linspace(16, 365, (365-16))
ydata = np.sin(2*np.pi*xdata/153) + np.cos(2*np.pi*xdata/127)
d = DataDisplayResampler(xdata, ydata)
fig, ax = plt.subplots()
# Hook up the line
d.line, = ax.plot(xdata, ydata, 'o-', ms=5)
d.update(ax) # Downsample the original view if needed
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Connect for changing the view limits
ax.callbacks.connect('xlim_changed', d.update)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment