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()
问题是每个矩形在图例中出现多个。我想在图例中只有两个条目:一个标记为“蓝色”的蓝色矩形和一个标记为“绿色”的绿色矩形。这怎么能实现呢?