对我来说,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()https://stackoverflow.com/questions/41338966
复制相似问题