# Plot smooth line with PyPlot

### Question

I've got the following simple script that plots a graph:

``````import matplotlib.pyplot as plt
import numpy as np

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

plt.plot(T,power)
plt.show()
``````

As it is now, the line goes straight from point to point which looks ok, but could be better in my opinion. What I want is to smooth the line between the points. In Gnuplot I would have plotted with `smooth cplines`.

Is there an easy way to do this in PyPlot? I've found some tutorials, but they all seem rather complex.

1
98
3/12/2011 4:06:38 PM

You could use `scipy.interpolate.spline` to smooth out your data yourself:

``````from scipy.interpolate import spline

xnew = np.linspace(T.min(),T.max(),300) #300 represents number of points to make between T.min and T.max

power_smooth = spline(T,power,xnew)

plt.plot(xnew,power_smooth)
plt.show()
``````

spline is deprecated in scipy 0.19.0, use Bspline class instead.

Switching from `spline` to `Bspline` isn't a straightforward copy/paste and requires a little tweaking:

``````from scipy.interpolate import make_interp_spline, BSpline

xnew = np.linspace(T.min(),T.max(),300) #300 represents number of points to make between T.min and T.max

spl = make_interp_spline(T, power, k=3) #BSpline object
power_smooth = spl(xnew)

plt.plot(xnew,power_smooth)
plt.show()
``````

142
11/27/2018 6:12:18 AM

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

``````from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()
``````

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.