python - 将代理图例句柄添加到现有图例

标签 python matplotlib legend

Matplotlib Legend Guide documentation有一个示例说明如何专门为图例创建代理艺术家。

在该示例中,专门创建了一个补丁用于在图例中显示。然后,补丁对象被传递到图例句柄(如果我正确解释了该示例)。

我的问题是,如果您已经执行了多个绘图实例,因此其中有大量内容,会发生什么:

plt.gca().get_legend_handles_labels()

你想做的事:

plt.legend()

然后将代理艺术家/内容添加到不在图形或轴中的图例中。

一个非常相似的问题是 here ,有一个答案从未被标记为正确,但似乎是我正在寻找的。不幸的是,作为一个低声誉用户,我无法对现有问题发表评论。 tacaswell 的答案暗示可以完成,但我无法解释此步骤:

"just add the patch object to the handles list as you would a Line2D object"

我有一些示例代码可以用来展示我的具体案例,但不确定它是否会帮助别人回答或只是使问题过于具体且难以解释。

感谢任何帮助或建议。

最佳答案

这句话

"just add the patch object to the handles list as you would a Line2D object"

按字面意思理解。假设您创建了一个 red_pa​​tch,并且有一个句柄 handles 列表,您可以添加 (+) 该 red_pa​​tch > 到句柄

plt.legend(handles=handles + [red_patch])

完整示例:

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

for i in range(3):
    plt.plot([0,1],[i,i+1], label=f"Label {i}")

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


handles, labels = plt.gca().get_legend_handles_labels()
# "just add the patch object to the handles list as you would a Line2D object"
plt.legend(handles=handles + [red_patch])

plt.show()

enter image description here

关于python - 将代理图例句柄添加到现有图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54776474/

相关文章:

python - 使用 matplotlib 按行绘制数组

python-3.x - 在 matplotlib 子图中添加一行

javascript - 将数组从 python 传输到 javascript

Python Pandas/tqdm 显示提取进度

python - 理解可变数量的参数?

r - ggplot 分开的图例和情节

R ggplot热图,多行在同一图形上具有单独的图例

python - 当满足条件时关闭 scrapy 蜘蛛并返回输出对象

python - 在给定的时间间隔内循环或包装颜色图

python - matplotlib 设置自己的轴值