将现有材料库图例添加到

2024-09-28 03:12:30 发布

您现在位置:Python中文网/ 问答频道 /正文

给定以下设置:

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作为参数,是否可以在不更改图例的其他属性的情况下,将自定义图例项添加到现有项之上的图例中?在

我可以使用以下方法添加项目:

^{pr2}$

但这并没有保留传说中位置的属性。在绘制线后,如何添加仅给定图例对象的项?在


Tags: fromimport属性plotmatplotlibasfigplt
2条回答

原则上,传奇并不意味着要更新,而是要重新创造。在

下面的代码可以满足您的需求,但是要注意这是一种使用内部方法的黑客攻击,因此不能保证能够正常工作,并且可能会在将来的版本中崩溃。所以不要在生产代码中使用它。此外,如果您为图例设置了与默认字体(大小)不同的标题,则在更新时它将丢失。另外,如果您通过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()

enter image description here

在绘制线条后添加色块,但在添加图例之前添加色块是一个选项吗?在

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')

相关问题 更多 >

    热门问题