2013-12-16 32 views
10

我正在運行模擬200次並將3個輸出列表繪製爲3行高透明度。這允許我顯示模擬之間的差異。Pyplot:僅顯示圖例中的前3行

問題是我的圖例顯示3x200項目,而不是3項。我怎樣才能讓它爲每一行顯示圖例?

for simulation in range(200): 
    plt.plot(num_s_nodes, label="susceptible", color="blue", alpha=0.02) 
    plt.plot(num_r_nodes, label="recovered", color="green", alpha=0.02) 
    plt.plot(num_i_nodes, label="infected", color="red", alpha=0.02) 
plt.legend() 
plt.show() 

回答

16

添加

plt.plot(... , label='_nolegend_') 

爲您不想在圖例中顯示的任何繪圖。所以在你的代碼例如可以做:

..., label='_nolegend_' if simulation else 'susceptible', ... 

同樣地,對於他人的,或者如果你不喜歡玄乎代碼:

..., label=simulation and '_nolegend_' or 'susceptible',... 
+2

設置'label = None'也應該有效。 – tacaswell

+0

@tacaswell設置'label = None'實際上是微妙的不同,並且不會從圖例中移除藝術家。例如:'plt.plot([0,1],[0,1],label = None); plt.plot([0,1],[1,0]); plt.legend(['justthislabel'])'會在圖例中顯示兩個項目。用'_nolegend_'替換'None'只能得到一個。 – oLas

8

爲避免你的繪圖,使用「代理」額外的邏輯您的傳奇作品的藝術家:

# no show lines for you ledgend 
plt.plot([], label="susceptible", color="blue", alpha=0.02) 
plt.plot([], label="recovered", color="green", alpha=0.02) 
plt.plot([], label="infected", color="red", alpha=0.02) 

for simulation in range(200): 
    # your actual lines 
    plt.plot(num_s_nodes, color="blue", alpha=0.02) 
    plt.plot(num_r_nodes, color="green", alpha=0.02) 
    plt.plot(num_i_nodes, color="red", alpha=0.02) 
plt.legend() 
plt.show() 
+0

關於這件事的好處是,如果你使用tex來解析你的線標籤,它也可以工作。我無法得到'_nolegend_'來解決這個問題。 – user35915