Sam Sam - 1 year ago 74
Python Question

Difference between get_lines() method of axes and legend

In the code

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]
evaluates to false even though they should be referring to the same line. May I know why this is the case?

Answer Source

The short answer is that they are different instances of objects in memory.

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>]

Notice that the id values are different, therefore, they are not truly "equal", even though they may "refer" to the same object in the plot.

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

Or, rather, ax1.get_lines() gives the line that is plotted and lg1.get_lines() gives the actual lines drawn in the legend box

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download