How to find out the value y for a specific x after fitting a polynomial line using polyfit?

Question:

I have fitted a polynomial line on a graph using poly1D. How can I determine the value of y of this polynomial line for a specific value of x?

draw_polynomial = np.poly1d(np.polyfit(x, y, 8))
polyline = np.linspace(min_x, max_x, 300)
plt.plot(polyline, draw_polynomial(polyline), color='purple')
plt.show()

Here, I want to find out the y if x = 6.

enter image description here

Asked By: Sunjaree

||

Answers:

You can directly call the fitted result p (polyline in your case) to get the y value. For example, x_val = 3.5, y_val_interp = round(p(x_val), 2) will give a y value of -0.36 in the code example below. I also added some annotations to visualize the result better.

import numpy as np
import numpy.polynomial.polynomial as npp
import matplotlib.pyplot as plt

# Since numpy version 1.4, the new polynomial API
# defined in numpy.polynomial is preferred.

x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
z = npp.polyfit(x, y, 4)

p = np.poly1d(np.flip(z))
xp = np.linspace(-2, 6, 100)

plt.plot(x, y, '.', markersize=12, zorder=2.01)
plt.plot(xp, p(xp), '-')
plt.xlim(-1, 6)
plt.ylim(-1.5, 1)

# interrupting y value based on x value
x_val = 3.5
y_val_interp = round(p(x_val), 2)

# add dashed lines
plt.plot([x_val, xp[0]], [y_val_interp, y_val_interp], '--', color='k')
plt.plot([x_val, x_val], [p(xp[0]), y_val_interp], '--', color='k')

# add annotation and marker
plt.annotate(f'(x={x_val}, y={y_val_interp})', (x_val, y_val_interp), size=12, xytext=(x_val * 1.05, y_val_interp))
plt.plot(x_val, y_val_interp, 'o', color='r', zorder=2.01)
print(f'x = {x_val}, y = {y_val_interp}')

plt.tight_layout()
plt.show()

enter image description here

References:

https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html

https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.Polynomial.fit.html#numpy.polynomial.polynomial.Polynomial.fit

https://numpy.org/doc/stable/reference/generated/numpy.poly1d.html

Answered By: コリン