简体   繁体   English

matplotlib.pyplot.plot 多项式数据显示多条随机线而不是多项式线

[英]matplotlib.pyplot.plot polynomial data showing several random lines instead of polynomial line

I have a polynomial function that outputs y from x (comes from a polynomial least squares fit).我有一个多项式函数,它从 x 输出 y(来自多项式最小二乘拟合)。 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我试图绘制这个以显示多项式连续曲线,如这里的一些答案所示: 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?我该如何纠正? 在此处输入图片说明

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. plot函数的默认行为是在你给它的点之间画线,按照你给它们的顺序。 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:如果您删除线条并仅在点的位置绘制标记( plt.plot(x, y, linestyle="", marker="o") ),您可以看到:

仅标记

Sorting the x array would let you get your desired output, but you would need to sort the y array into the same order.x数组进行排序可以让您获得所需的输出,但您需要将y数组排序为相同的顺序。 See How can I "zip sort" parallel numpy arrays?请参阅如何“压缩排序”并行 numpy 数组? for some ideas on how to do this.有关如何执行此操作的一些想法。

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).您的 x 数组和 y 数组是二维 (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.在我的回答中,我展示了使用 x 的排序索引作为参数以相同顺序对 y 值进行排序的三种方法。

Way 1:方式一:

plt.plot(sorted(x), y[np.argsort(x[:, 0])])

Way 2:方式二:

plt.plot(sorted(x), y[np.argsort(x.ravel())])

Way 3:方式3:

x_sorted = np.sort(x.ravel())
plt.plot(x_sorted, y[np.argsort(x_sorted)]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM