How can I plot a smooth curve using Matplotlib?

Matplotlib is a powerful library in Python that allows for the creation of high-quality visualizations. One of its key features is the ability to plot smooth curves. To plot a smooth curve using Matplotlib, you would first need to import the library and the necessary modules. Then, you can use the “plot” function to create a basic line graph. To make the curve smoother, you can use the “smooth” function and specify the degree of smoothing. Additionally, you can customize the curve by adjusting the color, line style, and marker style. With Matplotlib, creating a smooth, visually appealing curve is simple and efficient.

Plot a Smooth Curve in Matplotlib


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()

Smooth curve in Matplotlib

Note that the higher the degree you use for the 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()

Smooth curved spline in Matplotlib

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

x