轴的 get_lines() 方法与图例的区别

Difference between get_lines() method of axes and legend

在代码中

from matplotlib.figure import Figure

fig1 = Figure()
ax1 = fig1.add_subplot(111)
p1 = ax1.plot([1,2,3], label='123')
lg1 = ax1.legend()

lg1.get_lines()[0] == ax1.get_lines()[0] 计算结果为 false,即使它们应该指的是同一行。我可以知道为什么会这样吗?

简短的回答是它们是内存中对象的不同实例。

In [6]: lg1.get_lines()
Out[6]: [<matplotlib.lines.Line2D at 0x10e355828>]

In [7]: ax1.get_lines()
Out[7]: <a list of 1 Line2D objects>

In [8]: list(ax1.get_lines())
Out[8]: [<matplotlib.lines.Line2D at 0x10e342940>]

请注意,id 值不同,因此,它们不是真正的 "equal",即使它们可能 "refer" 是绘图中的同一对象。

In [9]: lg1.get_lines()[0]
Out[9]: <matplotlib.lines.Line2D at 0x10e355828>

In [10]: ax1.get_lines()[0]
Out[10]: <matplotlib.lines.Line2D at 0x10e342940>
In [11]: id(lg1.get_lines()[0])
Out[11]: 4533344296

In [12]: id(ax1.get_lines()[0])
Out[12]: 4533266752

或者更确切地说,ax1.get_lines() 给出绘制的线条,lg1.get_lines() 给出图例框中绘制的实际线条