手动添加图例项Python matplotlib [英] Manually add legend Items Python matplotlib

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

问题描述

我正在使用matlibplot,我想手动将图例中的颜色和标签项添加到图例中.我正在向图中添加数据,以指定在那里将导致大量重复.

I am using matlibplot and I would like to manually add items to the legend that are a color and a label. I am adding data to to the plot to specifying there would lead to a lot of duplicates.

我的想法是:

    ax2.legend(self.labels,colorList[:len(self.labels)])
    plt.legend()

其中self.labels是我想要的图例标签的数量,该标签需要较大的颜色列表的子集.但是,当我运行它时,它什么也不会产生.

Where self.labels is the number of items I want legend lables for that takes a subset of the large color list. However this yields nothing when I run it.

我想念什么吗?

谢谢

推荐答案

您是否已检查传奇指南?

出于实用性考虑,我引用了

For practicality, I quote the example from the guide.

并非所有句柄都可以自动转换为图例条目,因此它 通常是创建一个可以做到的艺术家所必需的.图例手柄不 必须在图形或轴上存在才能使用.

Not all handles can be turned into legend entries automatically, so it is often necessary to create an artist which can. Legend handles don’t have to exists on the Figure or Axes in order to be used.

假设我们要创建一个图例,其中包含一些数据条目 用红色表示:

Suppose we wanted to create a legend which has an entry for some data which is represented by a red color:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()

修改

要添加两个补丁,您可以执行以下操作:

To add two patches you can do this:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')

plt.legend(handles=[red_patch, blue_patch])

这篇关于手动添加图例项Python matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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