"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I smooth lines in Matplotlib for better visualization?

How can I smooth lines in Matplotlib for better visualization?

Published on 2024-11-10
Browse:694

How can I smooth lines in Matplotlib for better visualization?

Smoothing Lines in Matplotlib

In Matplotlib, plots typically connect data points with straight lines. While this may be acceptable in certain scenarios, the resulting graph may appear jagged or visually unappealing. This issue can be addressed by smoothing the lines, resulting in a more polished and informative visualization.

Using SciPy's Interpolation

To smooth lines in Matplotlib, you can leverage the capabilities of the SciPy library. By invoking scipy.interpolate.spline, you can generate an interpolation function that will produce a smooth curve that passes through the original data points.

from scipy.interpolate import spline

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

xnew = np.linspace(T.min(), T.max(), 300)  # Define the number of points for smoothing

power_smooth = spline(T, power, xnew)

plt.plot(xnew, power_smooth)

In SciPy versions 0.19.0 and later, spline has been deprecated and replaced by the BSpline class. To achieve similar results, you can employ the following code:

from scipy.interpolate import make_interp_spline, BSpline

spl = make_interp_spline(T, power, k=3)  # k=3 indicates cubic spline interpolation
power_smooth = spl(xnew)

plt.plot(xnew, power_smooth)

Visualizing the Smoothing Effects

The original plot with straight lines and the smoothed plot can be compared for clarity:

[Before](https://i.sstatic.net/dSLtt.png)
[After](https://i.sstatic.net/olGAh.png)

As evident from the images, smoothing the lines removes the jaggedness, resulting in a more visually appealing and informative graph.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3