2

Using numpy and matplotlib, I'm trying to plot a polyfitted set of data points:

x = [0, 5, 10, 15, 20]
y = [0, 0.07, 0.14, 0.2, 0.27]

Using this code:

import numpy as np 
import matplotlib.pyplot as plt
x = [0, 5, 10, 15, 20]
y = [0, 0.07, 0.14, 0.2, 0.27]

poly = np.polyfit(x, y, 1)
f = np.poly1d(poly)

plt.plot(f)
plt.show()

The variable f in the above code is 0.0134 x + 0.002. This polynomial, when plotted, is supposed to be leaning to the right. But when I plot it, it shows this: Plotted polyfit polynomial

What could be wrong with the code?

1
  • What happens when you plot y=f(x) versus x (instead of plotting f) Commented Feb 10, 2021 at 6:31

3 Answers 3

3

What you see is the plot of coefficients of linear function f, but not its values. This is the same as plotting two points:

plt.plot([0.0134, 0.002])

This happens because f is converted to list inside plt.plot:

print(list(f))
[0.0134, 0.002]

The points are displayed with coordinates (0, 0.0134) and (1, 0.002), because 0 and 1 are default x-values in plt.plot.

What you want is to to evaluate f at points x and plot its values:

plt.plot(x, [f(xi) for xi in x])

[f(xi) for xi in x] can be shortened just as f(x), because f can take list arguments, so that the code becomes:

plt.plot(x, f(x))

as already mentioned in other answers.

Because f is a linear function, just 2 points will be enough. x[0] is the first point and x[-1] is the last:

plt.plot([x[0], x[-1]], [f(x[0]), f(x[-1])])

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

You need to pass x values into the polynomial to get the corresponding y values:

plt.plot(x, f(x)) # this should solve your issue

Comments

1

If you print out f, that returns poly1d([0.0134, 0.002 ]). So if you try to plot that, it will draw a line between 0.0134 and 0.002 on the [0, 1] interval.

What you really want to do is evaluate f at x:

plt.plot(x, f(x))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.