在 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_patch
,并且有一个句柄 handles
列表,您可以添加 (+
) 该 red_patch
> 到句柄
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()
关于python - 将代理图例句柄添加到现有图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54776474/