在 matplotlib 中自定义图例 [英] Customizing legend in matplotlib

查看:118
本文介绍了在 matplotlib 中自定义图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 matplotlib 中绘制具有不同颜色的矩形.我希望每种类型的矩形都有一个在图例中出现一次的标签.我的代码是:

import matplotlib.patches 作为补丁fig1 = plt.figure()ax = plt.subplot(1,1,1)次数 = [0, 1, 2, 3, 4]对于 t 次:如果 % 2 == 0:颜色=蓝色"别的:颜色=绿色"ax.add_patch(patches.Rectangle((t, 0.5), 0.1, 0.1,脸色=颜色,标签=颜色))plt.xlim(times[0],times[-1] + 0.1)plt.legend()plt.show()

问题是每个矩形在图例中出现多个.我只想在图例中有两个条目:一个标记为蓝色"的蓝色矩形和一个标记为绿色"的绿色矩形.如何实现?

解决方案

如文档所述

i'm plotting rectangles that have different colors in matplotlib. i would like each type of rectangle to have a single label that appears once in the legend. my code is:

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()

the problem is that each rectangle appears multiple in the legend. i would like to only have two entries in the legend: a blue rectangle labeled "blue", and a green rectangle labeled "green". how can this be achieved?

解决方案

As documented here, you can control the legend by specifying the handles to the graphical objects for which you want the legends. In this case, two out of the five objects are needed, so you can store them in a dictionary

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()

这篇关于在 matplotlib 中自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆