2016-01-24 74 views
1

我繪製了matplotlib中具有不同顏色的矩形。我希望每種類型的矩形都有一個標籤出現在圖例中。我的代碼是:在matplotlib中定製圖例

import matplotlib.patches as patches 
fig1 = plt.figure() 
ax = plt.subplot(1,1,1) 
times = [0, 1, 2, 3, 4] 
for t in times: 
    if t % 2 == 0: 
     color="blue" 
    else: 
     color="green" 
    ax.add_patch(patches.Rectangle((t, 0.5), 0.1, 0.1, 
            facecolor=color, 
            label=color)) 
plt.xlim(times[0], times[-1] + 0.1) 
plt.legend() 
plt.show() 

問題是每個矩形在圖例中出現多個。我想在圖例中只有兩個條目:一個標記爲「藍色」的藍色矩形和一個標記爲「綠色」的綠色矩形。這怎麼能實現呢?

回答

0

如文檔here所示,您可以通過指定圖例對象的句柄來控制圖例。在這種情況下,兩個出五個對象的需要,這樣你就可以將它們存儲在一個字典

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
fig1 = plt.figure() 
ax = plt.subplot(1,1,1) 
times = [0, 1, 2, 3, 4] 
handle = {} 
for t in times: 
    if t % 2 == 0: 
     color="blue" 
    else: 
     color="green" 
    handle[color] = ax.add_patch(patches.Rectangle((t, 0.5), 0.1, 0.1, 
            facecolor=color, 
            label=color)) 
plt.xlim(times[0], times[-1] + 0.1) 
print handle 
plt.legend([handle['blue'],handle['green']],['MyBlue','MyGreen']) 
plt.show() 

enter image description here