Plotting Smooth Curves in matplotlib: A Python Guide to Signal Smoothing

Featured Img Smooth Curve

We’re going to learn how to build smooth curves using matplotlib and SciPy module.

Sometimes, you wish to get smooth curves for data visualization to make the plots look better and elegant. Fortunately, the same can be achieved with the help of matplotlib and SciPy module.

In this tutorial, we learn to plot smooth curves in Python using matplotlib and SciPy. We’ll start by importing the necessary modules, then prepare our data and construct a B-spline curve. Finally, we visualize the smooth curve using matplotlib. Let’s dive in!

Recommended read: Create animated plots in Python

Setting Up: Importing Necessary Modules and Defining Parameters

We first define the modules we’ll need for our plotting algorithm. We’ll import the required modules into our program. The modules that we are going to achieve our goal numpy, matplotlib and SciPy modules where numpy is required for data preparation, matplotlib for plotting simple plots, and SciPy to help out with smooth curves. By programming the ‘import numpy as np’ command, we can efficiently handle the input for our graph’s dimensions.

import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt

Step One: Preparing the Data

The parameters we’ll use are numpy arrays for their ease of handling, enabling us to compute our data efficiently. We would be plotting a sine wave where x coordinates are the x-axis value and y coordinates are the sine value of x. We will sample the noise in our time series data, which doesn’t always follow a smooth line.

x = np.array([i for i in range(50)])
y = np.array([np.sin(i) for i in x])

Step Two: Constructing the B-spline Curve

To generate a smooth curve and filter the noise, we interpolate the data using a B-spline kernel. This functional curve represents an average of our data. We pass in the x and y arrays as parameters, which returns the x and y coefficients together.

The next thing we need to do is to separate the coefficients from each other. The code below does the same for you.

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

Step Three: Visualizing the Smooth Curve

Now the last step is to plot the plot using the matplotlib library and the necessary functions and configurations to make the plot look better. The algorithm we use for plotting takes these coefficients to create an elegant visual representation of the data. Using matplotlib, we plot a curve that’s smooth. This smooth line is a more accurate representation of our data, despite the noisy variables that underlie the original dataset.

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="red")
plt.title("Smooth Sine Wave")
plt.xlabel("x values")
plt.ylabel("y values")
plt.show()

The final output plot is shown below.

Smooth B Spline Curve
Smooth B Spline Curve

Advanced Plotting: Showcasing Multiple Smooth Curves

Let’s use this same method to plot additional smooth curves, such as a sine wave along the x-axis, and show the magnitude of the changes with the new data. Using this same algorithm, we can generate multiple curves to explore more complex datasets. The following code plots a few more curves together with the help of subplot function of matplotlib.

plt.figure(figsize=(15,15))

plt.subplot(3, 3, 1)
x = np.array([i for i in range(30)])
y = np.array([np.tan(i) for i in x])

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="red")
plt.title("Smooth Tan Wave")
plt.xlabel("x values")
plt.ylabel("y values")

plt.subplot(3, 3, 2)
x = np.array([i for i in range(30)])
y = np.array([np.exp(i) for i in x])

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="green")
plt.title("Smooth e^x Wave")
plt.xlabel("x values")
plt.ylabel("y values")

plt.subplot(3, 3, 3)
x = np.array([i for i in range(10)])
y = np.array([np.sqrt(i) for i in x])

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="pink")
plt.title("Smooth sqrt Wave")
plt.xlabel("x values")
plt.ylabel("y values")

plt.subplot(3, 3, 4)
x = np.array([i for i in range(30)])
y = np.array([5**i for i in x])

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="black")
plt.title("Smooth 5^x Wave")
plt.xlabel("x values")
plt.ylabel("y values")

plt.subplot(3, 3, 5)
x = np.array([i for i in range(-10,10,1)])
y = np.array([i**2 -5 for i in x])

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="orange")
plt.title("Smooth X^2-5 Wave")
plt.xlabel("x values")
plt.ylabel("y values")

plt.subplot(3, 3, 6)
x = np.array([i for i in range(30)])
y = np.array([3**i + i for i in x])

B_spline_coeff = make_interp_spline(x, y)
X_Final = np.linspace(x.min(), x.max(), 500)
Y_Final = B_spline_coeff(X_Final)

plt.style.use('seaborn')
plt.plot(X_Final,Y_Final,color="magenta")
plt.title("Smooth 3^x+x Wave")
plt.xlabel("x values")
plt.ylabel("y values")

plt.show()

The output of the code is displayed below.

Multiple B Spline Curve
Multiple B Spline Curve

Summary

Congratulations! Today we learned plotting perfect smooth curves plots using matplotlib and SciPy modules. Applying a moving average and adjusting the smoothing parameter, we can specify how much we want to smooth the data. How will you utilize this in your next data visualization project?