簡體   English   中英

Matplotlib 不繪制某些數據..盡管 scatter 有效

[英]Matplotlib doesn't plot certain data..although scatter works

twenty = [[0.00186157 0.00201416 0.00216675 0.00213623 0.00253296 0.00250244  0.00280762 0.00292969 0.00308228 0.0032959  0.00338745 0.003479  0.003479   0.00341797 0.00335693 0.00320435 0.00308228 0.0027771  0.00253296 0.00216675]]
twentyfirst = [[0.00186157]]

以下函數 - 雖然它應該同時繪制散點圖和線圖,(這與頁面中的實現完全一樣)盡可能在標記中繪制兩者,但matplotlib在生成線中丟失。

def plot_time_series(twenty, twentyfirst):
    xlabel = np.arange(0, 1, 1./20).reshape(1,20)
    print(np.ones(twenty.shape[1])[np.newaxis,:].shape) #(1,20)
    A = np.vstack([xlabel, np.ones(twenty.shape[1])[np.newaxis,:]]).T

    m, c = np.linalg.lstsq(A, twenty.T)[0]
    print(m, c)
    plt.scatter(xlabel, twenty.T, c='b', label='data')
    ylabel = m*xlabel + c
    print(ylabel.shape) #(1,20)
    plt.plot(xlabel, ylabel, '-ok', label = 'fitted line')
    plt.legend(loc='best')
    plt.ylabel('amplitudes')
    plt.savefig('timeseries_problem2'+'_4')
    plt.close()

在此處輸入圖片說明

在幕后,這個問題詢問了繪圖之間的區別

plt.plot([[1,2,3]],[[2,3,1]])

plt.plot([[1],[2],[3]],[[2],[3],[1]])

在這兩種情況下,列表都是二維的。 在第一種情況下,您只有一行數據。 在第二種情況下,您只有一列數據。

文檔

x , y : 類似數組或標量
[...]
通常,這些參數是長度為 N 的數組。但是,也支持標量(相當於具有常量值的數組)。

參數也可以是二維的 然后,列代表單獨的數據集

重要的部分是最后一句話。 如果數據是二維的,如此處,它是按列解釋的。 由於行數組[[2,3,1]]由 3 列組成,每列都有一個值。 因此, plot將產生 3 條單“線”和一個點。 但是由於單個點不定義線,因此只有在激活標記時才可見,例如

plt.plot([[1,2,3]], [[2,3,1]], marker="o")

在此處輸入圖片說明

將此行數組轉置為列數組時,它將被解釋為具有 3 個條目的單個數據集。 因此,單行的預期結果

plt.plot([[1],[2],[3]], [[2],[3],[1]])

在此處輸入圖片說明

當然,將數組展平為 1D 同樣是可能的,

plt.plot(np.array([[1,2,3]]).flatten(), np.array([[2,3,1]]).flatten())

您可以輕松檢查您生產了多少行

print(len(plt.plot([[1,2,3]],[[2,3,1]])))            # prints 3
print(len(plt.plot([[1],[2],[3]],[[2],[3],[1]])))    # prints 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM