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