Home > Backend Development > Python Tutorial > How to Create a Smooth Line in a PyPlot Graph?

How to Create a Smooth Line in a PyPlot Graph?

Patricia Arquette
Release: 2024-11-01 17:48:30
Original
690 people have browsed it

How to Create a Smooth Line in a PyPlot Graph?

Plotting a Smooth Line in PyPlot

Problem:

When plotting a graph using PyPlot, the connecting lines between data points may appear rigid and discontinuous. This can be undesirable in certain scenarios.

Question:

How to smoothen the connecting lines in a PyPlot graph?

Solution:

To achieve a smoother line, one can utilize scipy's spline interpolation technique. Here's how:

<code class="python">import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate

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

# Create a dense array of points for interpolation
xnew = np.linspace(T.min(), T.max(), 300)

# Interpolate the data using a cubic spline
power_smooth = scipy.interpolate.spline(T, power, xnew)

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

Note: The 'spline' function in scipy is deprecated in version 0.19.0. Use the 'BSpline' class instead. Here's an updated version:

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

# Create a dense array of points for interpolation
xnew = np.linspace(T.min(), T.max(), 300)

# Create a B-spline interpolation object
spl = make_interp_spline(T, power, k=3)  # type: BSpline

# Evaluate the interpolation at the new points
power_smooth = spl(xnew)

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

The 'k' argument in 'make_interp_spline' controls the smoothness of the spline. Higher values of 'k' result in smoother lines.

The resulting plot will exhibit a smooth connecting line between data points, providing a more visually appealing representation of the data.

The above is the detailed content of How to Create a Smooth Line in a PyPlot Graph?. 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