Matplotlib plot is plotting the wrong way

Viewed 361

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?

3 Answers

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

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

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