11"""
2- ========
3- Resample
4- ========
2+ ===============
3+ Resampling Data
4+ ===============
55
6+ Downsampling lowers the sample rate or sample size of a signal. In
7+ this tutorial, the signal is downsampled when the plot is adjusted
8+ through dragging and zooming.
69"""
10+
711import numpy as np
812import matplotlib .pyplot as plt
913
@@ -13,18 +17,28 @@ class DataDisplayDownsampler(object):
1317 def __init__ (self , xdata , ydata ):
1418 self .origYData = ydata
1519 self .origXData = xdata
16- self .ratio = 5
20+ self .max_points = 50
1721 self .delta = xdata [- 1 ] - xdata [0 ]
1822
1923 def downsample (self , xstart , xend ):
20- # Very simple downsampling that takes the points within the range
21- # and picks every Nth point
24+ # get the points in the view range
2225 mask = (self .origXData > xstart ) & (self .origXData < xend )
23- xdata = self .origXData [mask ]
24- xdata = xdata [::self .ratio ]
26+ # dilate the mask by one to catch the points just outside
27+ # of the view range to not truncate the line
28+ mask = np .convolve ([1 , 1 ], mask , mode = 'same' ).astype (bool )
29+ # sort out how many points to drop
30+ ratio = max (np .sum (mask ) // self .max_points , 1 )
2531
32+ # mask data
33+ xdata = self .origXData [mask ]
2634 ydata = self .origYData [mask ]
27- ydata = ydata [::self .ratio ]
35+
36+ # downsample data
37+ xdata = xdata [::ratio ]
38+ ydata = ydata [::ratio ]
39+
40+ print ("using {} of {} visible points" .format (
41+ len (ydata ), np .sum (mask )))
2842
2943 return xdata , ydata
3044
@@ -37,8 +51,9 @@ def update(self, ax):
3751 self .line .set_data (* self .downsample (xstart , xend ))
3852 ax .figure .canvas .draw_idle ()
3953
54+
4055# Create a signal
41- xdata = np .linspace (16 , 365 , 365 - 16 )
56+ xdata = np .linspace (16 , 365 , ( 365 - 16 ) * 4 )
4257ydata = np .sin (2 * np .pi * xdata / 153 ) + np .cos (2 * np .pi * xdata / 127 )
4358
4459d = DataDisplayDownsampler (xdata , ydata )
@@ -51,5 +66,5 @@ def update(self, ax):
5166
5267# Connect for changing the view limits
5368ax .callbacks .connect ('xlim_changed' , d .update )
54-
69+ ax . set_xlim ( 16 , 365 )
5570plt .show ()
0 commit comments