2016-01-24 77 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