10.7 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonHow to Plot a Smooth Curve in Matplotlib

How to Plot a Smooth Curve in Matplotlib

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories