Speed up plotting magnified waveforms using Python & Matplotlib.pyplot


We can reduce the calculation time as the orange line in the following figure:


This page shows how to speed up plotting magnified waveforms in matplotlib.
By limiting the data before plotting, we can improve the performance of the matplotlib.
Especially, this method is suitable when the data range for plot is very short compared with the whole data range.
This page shows how to speed up plotting magnified waveforms in matplotlib.
By limiting the data before plotting, we can improve the performance of the matplotlib.
Especially, this method is suitable when the data range for plot is very short compared with the whole data range.
In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Sinusoidal wave with an noise is the example waveform.
In [2]:
xx = np.linspace(0,10,10**7)
yy = np.sin(2*np.pi*xx)
rr = 0.1 * np.random.randn(xx.shape[0])
yy = yy + rr
  • plot1 : without limiting data
  • plot2 : with limiting data
In [3]:
def plot1(x,y,x1,x2):
    y1,y2 = np.min(y),np.max(y)
    plt.plot(x,y,color="k",rasterized=True)
    plt.xlim(x1,x2)
    plt.ylim(y1,y2)
def plot2(x,y,x1,x2):
    y1,y2 = np.min(y),np.max(y)
    xp = x[np.where(np.logical_and( x1<x, x<x2 ))]
    yp = y[np.where(np.logical_and( x1<x, x<x2 ))]
    plt.plot(xp,yp,color="k",rasterized=True)
    plt.xlim(x1,x2)
    plt.ylim(y1,y2)
Case 1: plot range is whole range
In [4]:
st,en = 0,10
%timeit plot1(xx,yy,st,en)
1 loop, best of 3: 288 ms per loop
In [5]:
st,en = 0,10
%timeit plot2(xx,yy,st,en)
1 loop, best of 3: 432 ms per loop
Case 2: plot range is 0.1 times as much as whole range
In [6]:
st,en = 5,6
%timeit plot1(xx,yy,st,en)
1 loop, best of 3: 287 ms per loop
In [7]:
st,en = 5,6
%timeit plot2(xx,yy,st,en)
10 loops, best of 3: 90.6 ms per loop
Case 3: plot range is 0.01 times as much as whole range
In [8]:
st,en = 5,5.1
%timeit plot1(xx,yy,st,en)
1 loop, best of 3: 284 ms per loop
In [9]:
st,en = 5,5.1
%timeit plot2(xx,yy,st,en)
10 loops, best of 3: 55.1 ms per loop
Case 4: plot range is 0.001 times as much as whole range
In [10]:
st,en = 5,5.01
%timeit plot1(xx,yy,st,en)
1 loop, best of 3: 288 ms per loop
In [11]:
st,en = 5,5.01
%timeit plot2(xx,yy,st,en)
10 loops, best of 3: 50.6 ms per loop
Compare the Calculation time [ms] as functions of plotting range / whole range
In [12]:
plt.plot([1,0.1,0.01,0.001],[288,287,284,288],"o-")
plt.plot([1,0.1,0.01,0.001],[432,90.6,55.1,50.6],"o-")
plt.xscale("log")
plt.xlabel("plotting range / whole range")
plt.ylabel("Time [ms]")
plt.savefig("reduce_plotting_time.png",dpi=250,bbox_inches="tight",pad_inches=0.02)