Often you may want to plot a smooth curve in Matplotlib for a line chart. Fortunately this is easy to do with the help of the following SciPy functions:
This tutorial explains how to use these functions in practice.
Example: Plotting a Smooth Curve in Matplotlib
The following code shows how to create a simple line chart for a dataset:
import numpy as np import matplotlib.pyplot as plt #create data x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = np.array([4, 9, 12, 30, 45, 88, 140, 230]) #create line chart plt.plot(x,y) plt.show()
Notice that the line chart isn’t completely smooth since the underlying data doesn’t follow a smooth line. We can use the following code to create a smooth curve for this dataset:
from scipy.interpolate import make_interp_spline, BSpline #create data x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = np.array([4, 9, 12, 30, 45, 88, 140, 230]) #define x as 200 equally spaced values between the min and max of original x xnew = np.linspace(x.min(), x.max(), 200) #define spline spl = make_interp_spline(x, y, k=3) y_smooth = spl(xnew) #create smooth line chart plt.plot(xnew, y_smooth) plt.show()
Note that the higher the degree you use for the k argument, the more “wiggly” the curve will be. For example, consider the following chart with k=7:
from scipy.interpolate import make_interp_spline, BSpline #create data x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = np.array([4, 9, 12, 30, 45, 88, 140, 230]) #define x as 200 equally spaced values between the min and max of original x xnew = np.linspace(x.min(), x.max(), 200) #define spline with degree k=7 spl = make_interp_spline(x, y, k=7) y_smooth = spl(xnew) #create smooth line chart plt.plot(xnew, y_smooth) plt.show()
Depending on how curved you want the line to be, you can modify the value for k.
Additional Resources
How to Show Gridlines on Matplotlib Plots
How to Remove Ticks from Matplotlib Plots
How to Create Matplotlib Plots with Log Scales