0
對我來說確實需要對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()