2015-05-06 80 views
0

我必須在單個圖上繪製多條線和它們的曲線擬合線。所有這些行都使用for循環繪製。由於它是使用循環進行繪製,因此後續步驟的曲線擬合線將繪製在其前一個繪圖上,如圖所示。 enter image description here如何在Python中將標記放置在標記下方?

的重複性代碼:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) 
y = np.array([[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24], 
      [6, 5.2, 8.5, 9.1, 13.4, 15.1, 16.1, 18.3, 20.4, 22.1, 23.7]]) 

m, n = x.shape 

figure = plt.figure(figsize=(5.15, 5.15)) 
figure.clf() 
plot = plt.subplot(111) 
for i in range(m): 
    poly = np.polyfit(x[i, :], y[i, :], deg =1) 
    plt.plot(poly[0] * x[i, :] + poly[1], linestyle = '-') 
for i in range(m): 
    plt.plot(x[i, :], y[i, :], linestyle = '', marker = 'o', markersize = 20) 
plot.set_ylabel('Y', labelpad = 6) 
plot.set_xlabel('X', labelpad = 6) 
plt.show() 

這給了我下面的標記的所有擬合線:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) 
y = np.array([[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24], 
      [6, 5.2, 8.5, 9.1, 13.4, 15.1, 16.1, 18.3, 20.4, 22.1, 23.7]]) 

m, n = x.shape 

figure = plt.figure(figsize=(5.15, 5.15)) 
figure.clf() 
plot = plt.subplot(111) 
for i in range(m): 
    poly = np.polyfit(x[i, :], y[i, :], deg =1) 
    plt.plot(poly[0] * x[i, :] + poly[1], linestyle = '-') 
    plt.plot(x[i, :], y[i, :], linestyle = '', marker = 'o', markersize = 20) 
plot.set_ylabel('Y', labelpad = 6) 
plot.set_xlabel('X', labelpad = 6) 
plt.show() 

我可以用另一個循環爲解決這個問題。

enter image description here

但是,有沒有在Python/matplotlib任何內置功能來做到這一點,而無需使用兩個循環?

更新

僅作爲示例我已經使用N = 2,n可以是大於2,即,環路將被運行多次。

更新2回答

後,我能爲同一行也這樣做呢?作爲一個例子:

plt.plot(x[i, :], y[i, :], linestyle = ':', marker = 'o', markersize = 20) 

我可以給linestyle一個zorder = 1和標記一個zorder = 3嗎?

+0

'plt.plot'採用'zorder'參數將元素放在前面(或後面)。 – cphlewis

回答

1

編輯只是你的繪圖線:

plt.plot(poly[0] * x[i, :] + poly[1], linestyle = '-', 
      zorder=-1) 
    plt.plot(x[i, :], y[i, :], linestyle = '', marker = 'o', markersize = 20, 
      zorder=3) 

現在標記都在行的前面,雖然標記/線組內他們仍然訂單的-繪圖。

更新

對改變的問題(TSK!)的回答:否。一個電話plot,一個zorder參數。

如果要在循環的每次通過中匹配標記和線條的顏色和樣式,請爲每個通道設置一個迭代器或生成器並獲取current_color,然後將其用作plot調用的參數。