进行以下设置:
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
作为参数,是否可以在不更改图例其他属性的情况下将自定义图例项添加到现有项顶部的图例中? >
我可以使用以下方法添加项目:
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。绘制线条后,如何只给图例对象添加项目?
答案 0 :(得分:1)
在绘制线条之后但在添加图例之前是否添加了色块?
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
fig, ax = plt.subplots()
line1 = ax.plot([0,1,2,3,4,5,6], label='linear')
line2 = ax.plot([0,1,4,9,16,25,36], label='square')
patch = Patch(facecolor='orange', edgecolor='r', label='Color patch')
lgd = ax.legend(handles=[line1, line2, patch], loc='lower right')
答案 1 :(得分:1)
原则上,图例不是要更新的,而是要重新创建的。
以下内容将满足您的要求,但请注意,这是使用内部方法的黑客,因此不能保证能正常工作,并且可能会在将来的发行版中破坏。因此,请勿在生产代码中使用它。另外,如果您为图例设置的标题使用的字体(大小)与默认字体不同,则更新后该标题将丢失。另外,如果您通过markerfirst
操作了句柄和标签的顺序,则更新后将丢失它们。
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()