将项目添加到现有的Matplotlib图例 [英] Add item to existing Matplotlib legend
问题描述
进行以下设置:
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2,3,4,5,6], label='linear')
ax.plot([0,1,4,9,16,25,36], label='square')
lgd = ax.legend(loc='lower right')
如果函数add_patch
仅接收lgd
作为参数,是否可以将自定义图例项添加到现有项顶部的图例中,而无需更改图例的其他属性?
If a function add_patch
receives only lgd
as an argument, can a custom legend item be added to the legend on top of the existing items, without changing the other properties of the legend?
我可以使用以下方法添加项目:
I was able to add an item using:
def add_patch(legend):
from matplotlib.patches import Patch
ax = legend.axes
handles, labels = ax.get_legend_handles_labels()
handles.append(Patch(facecolor='orange', edgecolor='r'))
labels.append("Color Patch")
ax.legend(handles=handles, labels=labels)
但这不会保留图例之类的属性,例如location.绘制线条后,如何只给图例对象添加项目?
But this does not preserve the properties of the legend like location. How can I add an item given only the legend object after lines have been plotted?
推荐答案
原则上,图例不是要更新的,而是要重新创建的.
In principle a legend is not meant to be updated, but recreated instead.
以下内容将满足您的需求,但请注意,这是使用内部方法的黑客,因此不能保证能正常工作,并且可能在将来的发行版中破坏.因此,请勿在生产代码中使用它.另外,如果您为图例设置的标题使用的字体(大小)与默认字体不同,则更新后该标题将丢失.另外,如果您通过markerfirst
操纵了手柄和标签的顺序,那么更新后该信息将丢失.
The following would do what you're after, but beware that this is a hack which uses internal methods and is hence not guaranteed to work and might break in future releases. So don't use it in production code. Also, if you have set a title to the legend with a different font(size) than default, it will be lost upon updating. Also, if you have manipulated the order of handles and labels via markerfirst
, this will be lost upon updating.
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2,3,4,5,6], label='linear')
ax.plot([0,1,4,9,16,25,36], label='square')
lgd = ax.legend(loc='lower right')
def add_patch(legend):
from matplotlib.patches import Patch
ax = legend.axes
handles, labels = ax.get_legend_handles_labels()
handles.append(Patch(facecolor='orange', edgecolor='r'))
labels.append("Color Patch")
legend._legend_box = None
legend._init_legend_box(handles, labels)
legend._set_loc(legend._loc)
legend.set_title(legend.get_title().get_text())
add_patch(lgd)
plt.show()
这篇关于将项目添加到现有的Matplotlib图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!