2016-12-27 60 views
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() 

回答

1

的值的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')