Why does get_legend_handles_labels() return empty lists when legend labels are added via ax.legend()

Viewed 1041

After the following common code:

import math
import matplotlib.pyplot as plt
x = [x for x in range(10)]
y = [math.sin(x) for x in x]

The following two code snippets produce the exact same plot:

ax = plt.subplot()
ax.scatter(x,y,label='AAA')
ax.legend()
print('ax.get_legend_handles_labels() returns:\n',ax.get_legend_handles_labels())
plt.show()
ax = plt.subplot()
ax.scatter(x,y)
ax.legend(labels=['AAA'])
print('ax.get_legend_handles_labels() returns:\n',ax.get_legend_handles_labels())
plt.show()

The print statement from the first snippet returns

ax.get_legend_handles_labels() returns:
 ([<matplotlib.collections.PathCollection object at 0x7fc32cbdfac0>], ['AAA'])

but the second snippet gives:

ax.get_legend_handles_labels() returns:
 ([], [])

Why does get_legend_handles_labels() return empty lists in the second case, yet the resulting plot is identical?


0 Answers
Related