Reputation: 75
I have a polynomial function that outputs y from x (comes from a polynomial least squares fit). I tried to plot this to show a polynomial continuous curve as shown in some of the answers here: Plotting a polynomial using Matplotlib and coeffiecients
My code can be reduced down to:
import numpy as np
import matplotlib.pyplot as plt
y = np.array([[-0.02200175],
[-0.20964548],
[ 0.68482722],
[-0.30177928],
[ 0.49887387],
[-0.23443495],
[ 0.62761791],
[ 0.94930752],
[ 0.82429792],
[ 0.20244308]])
x = np.array([[ 0.77123627],
[ 0.84008558],
[-0.39987312],
[-0.85321811],
[ 0.53479747],
[-0.83009557],
[ 0.45752816],
[-0.10422071],
[ 0.30249733],
[-0.66099626]])
plt.plot(x, y)
The output, instead of a continuous curve, is a bunch of lines between the points. Why is this? How can I correct it?
Upvotes: 0
Views: 1033
Reputation: 39052
The problem is as stated in the other answer. My answer shows how you can plot in a sorted manner. You x-array and y-array are 2 dimensional (10 x 1). In my answer, I am showing three ways to use the sorted indices of x as an argument to sort the y-values in the same order.
Way 1:
plt.plot(sorted(x), y[np.argsort(x[:, 0])])
Way 2:
plt.plot(sorted(x), y[np.argsort(x.ravel())])
Way 3:
x_sorted = np.sort(x.ravel())
plt.plot(x_sorted, y[np.argsort(x_sorted)])
Upvotes: 2
Reputation: 2145
The problem is that your points are out of order. The plot
function's default behavior is to draw lines between the points you give it, in the order you gave them. Your points lie on a parabola, but are not in order from left to right (or right to left, it wouldn't matter which you used).
If you remove the lines and just draw markers at the positions of the points instead (plt.plot(x, y, linestyle="", marker="o")
), you can see this:
Sorting the x
array would let you get your desired output, but you would need to sort the y
array into the same order. See How can I "zip sort" parallel numpy arrays? for some ideas on how to do this.
Upvotes: 1