Home > Backend Development > Python Tutorial > How to Smooth a Line Plot in Python using PyPlot and Scipy?

How to Smooth a Line Plot in Python using PyPlot and Scipy?

Susan Sarandon
Release: 2024-11-02 16:04:02
Original
574 people have browsed it

Smoothing a Line Plot with PyPlot

PyPlot's default line plot method connects data points with straight lines. This approach can result in jagged lines, especially when dealing with large datasets. Fortunately, there is an easy way to smooth out these lines using scipy.interpolate.spline.

<code class="python"># Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline

# Define data arrays
T = np.array([6, 7, 8, 9, 10, 11, 12])
power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])

# Generate a smoothed spline
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)

# Plot the smoothed line
plt.plot(xnew, power_smooth)
plt.show()</code>
Copy after login

Before smoothing:
How to Smooth a Line Plot in Python using PyPlot and Scipy?

After smoothing:
How to Smooth a Line Plot in Python using PyPlot and Scipy?

Alternatively, you can use BSpline from scipy.interpolate.make_interp_spline for a more modern approach:

<code class="python"># Import make_interp_spline and BSpline
from scipy.interpolate import make_interp_spline, BSpline

# Generate a smoothed spline using BSpline
spl = make_interp_spline(T, power, k=3)
power_smooth = spl(xnew)

# Plot the smoothed line
plt.plot(xnew, power_smooth)
plt.show()</code>
Copy after login

The above is the detailed content of How to Smooth a Line Plot in Python using PyPlot and Scipy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template