Home > Article > Backend Development > How to Smooth a Line Plot in Python using PyPlot and Scipy?
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>
Before smoothing:
After smoothing:
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>
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!