排序的散点图不同于未排序的散点图

Sorted scatter plot differs from unsorted one

plt.plot 需要排序对我来说确实有意义,但是需要排序的散点图 (plt.scatter) 似乎很奇怪。我在这个脚本中遇到了这个问题。脚本本身并不重要,只是作为一个最小的工作示例。重要的是 scatter 的行为,即 plt.scatter(sorted(l2), Y) 将给出与 plt.scatter(l2, Y) 不同的结果。这是为什么?对我来说毫无意义。

import matplotlib.pyplot as plt
import numpy as np
from math import log, exp, isnan
from sys import argv
from random import randint

def generate_linear_regression_line(X, Y):
    X_ = np.mean(X)
    XX_ = np.mean(map(lambda x:x*x,X))
    Y_ = np.mean(Y)
    XY_ = map(lambda x,y:x*y,X,Y)
    m = np.mean((X_ * Y_ - XY_) / (X_**2 - XX_))
    b = Y_ - m * X_
    print m
    print b
    return lambda x : m * x + b

max = int(argv[1])

l1 = [randint(1, max) for i in range(max)]
# l2 = range(0,max)
l2 = []
maxentry = 0
while len(l2) != max:
    n = randint(max, 2*max)
    if n not in l2:
        if n > maxentry:
            maxentry = n
        l2.append(n)
assert(maxentry >= len(l1))

assert(len(l2) == len(l1))


regl = generate_linear_regression_line(l2, l1)

X = []
Y = []
for i in range(len(l2)):
    X.append(i)
    Y.append(regl(i))

print sum(l1)
print sum(Y)

assert(len(Y) == len(l1))
# assert(sum(Y) > sum(l1))

plt.scatter(l2, l1)
plt.plot(X, Y, c='red')
plt.scatter(sorted(l2), Y, c='green')
plt.xlabel('L2')
plt.ylabel('L1')
plt.show()

Y中值的顺序取决于L2中值的顺序,例如,(L2[0], Y[0])表示一个点。当您对 L2 进行排序时,您会重新排序 L2 而不会重新排序 Y.

您可以压缩两个数组,对它们进行排序并制作散点图,例如:

import itertools
P = sorted(itertools.izip(L2, Y))
L2s, Ys = zip(*P)
plt.scatter(L2s, Ys, c='green')