Reputation: 917
I need to change this into a smooth line
import matplotlib.pyplot as plt
plt.plot([8.714871428, 8.618221961,8.338674976,7.904714805,6.73505356,6.08059523,5.423472376,4.785585409,3.615895343])
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.show()
Can I make it smooth as Excel can make by default?
Upvotes: 0
Views: 6626
Reputation: 6806
If you want to connect the points with a smooth curve then you have to do interpolation not just any curve fitting. One of the easiest method is spline fitting which you can do using scipy.interpolate
.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.interpolate import splrep, splev
>>> y = [8.714871428, 8.618221961, 8.338674976, 7.904714805, 6.73505356, 6.08059523, 5.423472376, 4.785585409, 3.615895343]
>>> x = np.arange(len(y))
>>> tck = splrep(x, y)
>>> xnew = np.linspace(x[0], x[-1])
>>> ynew = splev(xnew, tck)
>>> plt.plot(xnew, ynew)
[<matplotlib.lines.Line2D object at 0x7f0c6dbbd090>]
>>> plt.plot(x, y, 'o')
[<matplotlib.lines.Line2D object at 0x7f0c6d8f5150>]
>>> plt.show()
Upvotes: 4
Reputation: 31399
The easiest way to get a smooth curve is probably fitting a polynomial. Below is an example for a polynomial fit of degree 3.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 8, 1000)
x_knots = list(range(0,9))
y_knots = [
8.714871428, 8.618221961, 8.338674976,
7.904714805, 6.73505356, 6.08059523,
5.423472376, 4.785585409, 3.615895343
]
poly_deg = 3
coefs = np.polyfit(x_knots, y_knots, poly_deg)
y_poly = np.polyval(coefs, x)
plt.plot(x_knots, y_knots, "o", label="data points")
plt.plot(x, y_poly, label="polynomial fit")
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.legend()
Upvotes: 3