See the example
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
print(mpl.__version__)
fig, ax = plt.subplots()
ax.plot([1, 2], [1, 2])
ax.legend(
[(Line2D([], [], color="C0", label="0"), Patch(color="C0", alpha=0.5, label="0"))],
["Label"]
)
legend = ax.get_legend()
handles = legend.legend_handles
print(handles)
[<matplotlib.lines.Line2D object at 0x7fa78a933310>]
I would expect it to be a list with a tuple of length 2: [(Line2D, Patch)]
but this only shows [Line2D]
. I looked into the documentation but I didn’t find this explained. I’m not sure if this is how it is supposed to work, or if it is a bug.
print(mpl.__version__)
# 3.7.0.dev1147+ge9d1f9c066
Note It looks like it keep only the first object. See the modification
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
fig, ax = plt.subplots()
ax.plot([1, 2], [1, 2])
ax.legend(
[(Patch(color="C0", alpha=0.5, label="0"), Line2D([], [], color="C0", label="0"))],
["Label"]
)
legend = ax.get_legend()
handles = legend.legend_handles
print(handles)
[<matplotlib.patches.Rectangle object at 0x7fa78a8aac40>]