We can reduce the calculation time as the orange line in the following figure:
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.
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.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
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
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)
st,en = 0,10
%timeit plot1(xx,yy,st,en)
st,en = 0,10
%timeit plot2(xx,yy,st,en)
st,en = 5,6
%timeit plot1(xx,yy,st,en)
st,en = 5,6
%timeit plot2(xx,yy,st,en)
st,en = 5,5.1
%timeit plot1(xx,yy,st,en)
st,en = 5,5.1
%timeit plot2(xx,yy,st,en)
st,en = 5,5.01
%timeit plot1(xx,yy,st,en)
st,en = 5,5.01
%timeit plot2(xx,yy,st,en)
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)