I am trying to plot a line in matplotlib.. I am searching for the right type of interpolation.. I want something like this
where every line is smoothed. I tried several combination of scipy and matplotlib, such as
x_new = np.arange(x, x_length, 1)
tck = interpolate.splrep(x, y, s=3)
y_new = interpolate.splev(x_new, tck, der=0)
ax.plot(x_new, y_new, color+lstyle)
but the best result I get is
The line represents an increasing variable.. so it is a wrong representation. What can I search for?
Thanks
Edit: I am thinking about implementing a method from myself, but I don't know if it has been already done.. pseudo code is the following
take x and y
calculate spline for each three points
x[0], x[1], x[2] ... x[1], x[2], x[3] ... and so on
for each y[n] sums every computation done for it and divide by number of
computations (i.e. y[1] is computed for triplette x[0..2] and x[1..3] so the
sum is divided by two (average for each point is taken as its value)
How to plot a smooth line with matplotlib? Set the figure size and adjust the padding between and around the subplots. Create a list of data points, x and y. Plot the x and y data points.
Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot (), which is used to plot two-dimensional data. Different functions used are explained below: np.arange (start, end): This function returns equally spaced values from the interval [start, end).
Plot line graph from NumPy array. For plotting graphs in Python we will use the Matplotlib library. Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot (), which is used to plot two-dimensional data. Different functions used are explained below:
From matplotlib we use the specific function i.e. pyplot (), which is used to plot two-dimensional data. Different functions used are explained below: np.arange (start, end): This function returns equally spaced values from the interval [start, end). plt.title (): It is used to give a title to the graph.
For that type of graph, you want monotonic interpolation. The PchipInterpolator
class (which you can refer to by its shorter alias pchip
) in scipy.interpolate can be used:
import numpy as np
from scipy.interpolate import pchip
import matplotlib.pyplot as plt
# Data to be interpolated.
x = np.arange(10.0)
y = np.array([5.0, 10.0, 20.0, 15.0, 13.0, 22.0, 20.0, 15.0, 12.0, 16.0])
# Create the interpolator.
interp = pchip(x, y)
# Dense x for the smooth curve.
xx = np.linspace(0, 9.0, 101)
# Plot it all.
plt.plot(xx, interp(xx))
plt.plot(x, y, 'bo')
plt.ylim(0, 25)
plt.grid(True)
plt.show()
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With