Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions doc/release/next_whats_new/patchcollection_legend.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
``PatchCollection`` legends now supported
------------------------------------------
`.PatchCollection` instances now properly display in legends when given a label.
Previously, labels on `~.PatchCollection` objects were ignored by the legend
system, requiring users to create manual legend entries.

The legend entry displays a rectangle matching the visual properties (colors,
line styles, line widths) of the first patch in the collection.

.. code-block:: python

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection

fig, ax = plt.subplots()
patches = [mpatches.Circle((0, 0), 0.1), mpatches.Rectangle((0.5, 0.5), 0.2, 0.3)]
pc = PatchCollection(patches, facecolor='blue', edgecolor='black', label='My patches')
ax.add_collection(pc)
ax.legend() # Now displays the label "My patches"
plt.show()
Comment thread
story645 marked this conversation as resolved.
Resolved

This fix resolves :ghissue:`23998`.
3 changes: 2 additions & 1 deletion lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
StepPatch)
from matplotlib.collections import (
Collection, CircleCollection, LineCollection, PathCollection,
Collection, CircleCollection, LineCollection, PatchCollection, PathCollection,
PolyCollection, RegularPolyCollection)
from matplotlib.text import Text
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
Expand Down Expand Up @@ -787,6 +787,7 @@ def draw(self, renderer):
BarContainer: legend_handler.HandlerPatch(
update_func=legend_handler.update_from_first_child),
tuple: legend_handler.HandlerTuple(),
PatchCollection: legend_handler.HandlerPatchCollection(),
PathCollection: legend_handler.HandlerPathCollection(),
PolyCollection: legend_handler.HandlerPolyCollection()
}
Expand Down
17 changes: 17 additions & 0 deletions lib/matplotlib/legend_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -809,3 +809,20 @@ def create_artists(self, legend, orig_handle,
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]


class HandlerPatchCollection(HandlerPolyCollection):
"""
Handler for `.PatchCollection` instances.

This handler creates a rectangular legend entry that matches the visual
properties (colors, line styles, etc.) of the first patch in the collection.

See Also
--------
matplotlib.collections.PatchCollection : The collection class this handles.
"""
# PatchCollection and PolyCollection have the same API for accessing
# colors, line properties, etc., so we can reuse HandlerPolyCollection
# implementation directly via inheritance.
pass

@story645 story645 Nov 19, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason to bother w/ a new class vs. just directly registering, e.g.:

 PatchCollection: legend_handler.HandlerPolyCollection()

@FazeelUsmani FazeelUsmani Nov 20, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no reason. PatchCollection and PolyCollection have identical APIs for accessing colors and line properties, so we can just register HandlerPolyCollection directly. I'll remove the new class.

2 changes: 2 additions & 0 deletions lib/matplotlib/legend_handler.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,5 @@ class HandlerPolyCollection(HandlerBase):
fontsize: float,
trans: Transform,
) -> Sequence[Artist]: ...

class HandlerPatchCollection(HandlerPolyCollection): ...
77 changes: 77 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1667,3 +1667,80 @@ def test_boxplot_legend_labels():
bp4 = axs[3].boxplot(data, label='box A')
assert bp4['medians'][0].get_label() == 'box A'
assert all(x.get_label().startswith("_") for x in bp4['medians'][1:])


def test_patchcollection_legend():
# Test that PatchCollection labels show up in legend (issue #23998)
fig, ax = plt.subplots()

pc = mcollections.PatchCollection(
[
mpatches.Polygon([[0, 0], [100, 100], [200, 0]]),
mpatches.Polygon([[400, 0], [500, 100], [600, 0]]),
],
label="patch collection", facecolor='blue', edgecolor='black'
)
ax.add_collection(pc, autolim=True)
ax.autoscale_view()

leg = ax.legend()

# Check that the legend contains our label
assert len(leg.get_texts()) == 1
assert leg.get_texts()[0].get_text() == "patch collection"

# Check that the legend handle exists and has correct colors
assert len(leg.legend_handles) == 1
legend_patch = leg.legend_handles[0]
assert_allclose(legend_patch.get_facecolor()[:3],
pc.get_facecolor()[0][:3], rtol=1e-5)
assert_allclose(legend_patch.get_edgecolor()[:3],
pc.get_edgecolor()[0][:3], rtol=1e-5)


def test_patchcollection_legend_properties():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can combine test_patchcollection_legend: and test_patchcollection_legend_properties(): b/c text is just another property

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

# Test that PatchCollection legend preserves visual properties
fig, ax = plt.subplots()

pc = mcollections.PatchCollection(
[mpatches.Circle((0, 0), 1), mpatches.Circle((2, 0), 1)],
label="styled patches",
facecolor='red',
edgecolor='blue',
linewidths=3,
linestyle='--',
)
ax.add_collection(pc)
ax.autoscale_view()

leg = ax.legend()

# Verify that visual properties are preserved
legend_patch = leg.legend_handles[0]
assert_allclose(legend_patch.get_facecolor()[:3],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is alpha getting ignored here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It shouldn't be. The alpha channel should also be verified. I'll change it to check all 4 RGBA components instead of just RGB.

pc.get_facecolor()[0][:3], rtol=1e-5)
assert_allclose(legend_patch.get_edgecolor()[:3],
pc.get_edgecolor()[0][:3], rtol=1e-5)
assert legend_patch.get_linewidth() == pc.get_linewidths()[0]
assert legend_patch.get_linestyle() == pc.get_linestyles()[0]


def test_patchcollection_legend_empty():
# Test that empty PatchCollection doesn't crash
fig, ax = plt.subplots()

# Create an empty PatchCollection
pc = mcollections.PatchCollection([], label="empty collection")
ax.add_collection(pc)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this matter if you're just testing object properties?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it doesn't matter. Since we're only testing that the legend handler creates the correct objects with the right properties, the axis limits aren't needed. I'll remove these lines.

# This should not crash
leg = ax.legend()

# Check that the label still appears
assert len(leg.get_texts()) == 1
assert leg.get_texts()[0].get_text() == "empty collection"

# The legend handle should exist
assert len(leg.legend_handles) == 1
Loading