Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7ed9875

Browse files
Faruk Fakihrcomer
Faruk Fakih
authored andcommitted
Created handler for PatchCollection
1 parent f533687 commit 7ed9875

File tree

5 files changed

+88
-2
lines changed

5 files changed

+88
-2
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Legend handler for PatchCollection objects
2+
------------------------------------------
3+
4+
PatchCollection objects are now supported in legends. The feature can be used as follows:
5+
6+
.. plot::
7+
:include-source: true
8+
9+
import matplotlib.pyplot as plt
10+
from matplotlib.collections import PatchCollection
11+
from matplotlib.patches import Polygon
12+
13+
fig, axs = plt.subplots()
14+
p1, p2 = Polygon([[0, 0], [100, 100], [200, 0]]), Polygon([[400, 0], [500, 100], [600, 0]])
15+
p3, p4 = Polygon([[700, 0], [800, 100], [900, 0]]), Polygon([[1000, 0], [1100, 100], [1200, 0]])
16+
p = PatchCollection([p1, p2], label="a", facecolors='red', edgecolors='black')
17+
p2 = PatchCollection([p3, p4], label="ab", color='green')
18+
axs.add_collection(p, autolim=True)
19+
axs.add_collection(p2, autolim=True)
20+
axs.set_xlim(right=1200)
21+
axs.set_ylim(top=100)
22+
axs.legend()
23+
24+
plt.show()

lib/matplotlib/legend.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
StepPatch)
3939
from matplotlib.collections import (
4040
Collection, CircleCollection, LineCollection, PathCollection,
41-
PolyCollection, RegularPolyCollection)
41+
PolyCollection, PatchCollection, RegularPolyCollection)
4242
from matplotlib.text import Text
4343
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
4444
from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
@@ -792,6 +792,7 @@ def draw(self, renderer):
792792
Patch: legend_handler.HandlerPatch(),
793793
StepPatch: legend_handler.HandlerStepPatch(),
794794
LineCollection: legend_handler.HandlerLineCollection(),
795+
PatchCollection: legend_handler.HandlerPatchCollection(),
795796
RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
796797
CircleCollection: legend_handler.HandlerCircleCollection(),
797798
BarContainer: legend_handler.HandlerPatch(

lib/matplotlib/legend_handler.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,32 @@ def create_artists(self, legend, orig_handle,
427427
return [legline]
428428

429429

430+
class HandlerPatchCollection(HandlerPatch):
431+
"""
432+
Handler for `.PatchCollection` instances.
433+
"""
434+
def _default_update_prop(self, legend_handle, orig_handle):
435+
lw = orig_handle.get_linewidths()[0]
436+
dashes = orig_handle._us_linestyles[0]
437+
facecolor = orig_handle.get_facecolor()[0]
438+
edgecolor = orig_handle.get_edgecolor()[0]
439+
legend_handle.set_facecolor(facecolor)
440+
legend_handle.set_edgecolor(edgecolor)
441+
legend_handle.set_linestyle(dashes)
442+
legend_handle.set_linewidth(lw)
443+
444+
def create_artists(self, legend, orig_handle,
445+
xdescent, ydescent, width, height, fontsize, trans):
446+
447+
p = self._create_patch(legend, orig_handle,
448+
xdescent, ydescent, width, height, fontsize)
449+
450+
self.update_prop(p, orig_handle, legend)
451+
p.set_transform(trans)
452+
453+
return [p]
454+
455+
430456
class HandlerRegularPolyCollection(HandlerNpointsYoffsets):
431457
r"""Handler for `.RegularPolyCollection`\s."""
432458

lib/matplotlib/legend_handler.pyi

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ class HandlerStepPatch(HandlerBase):
130130
trans: Transform,
131131
) -> Sequence[Artist]: ...
132132

133-
class HandlerLineCollection(HandlerLine2D):
133+
class HandlerLineCollection(HandlerPatch):
134134
def get_numpoints(self, legend: Legend) -> int: ...
135135
def create_artists(
136136
self,
@@ -144,6 +144,19 @@ class HandlerLineCollection(HandlerLine2D):
144144
trans: Transform,
145145
) -> Sequence[Artist]: ...
146146

147+
class HandlerPatchCollection(HandlerLine2D):
148+
def create_artists(
149+
self,
150+
legend: Legend,
151+
orig_handle: Artist,
152+
xdescent: float,
153+
ydescent: float,
154+
width: float,
155+
height: float,
156+
fontsize: float,
157+
trans: Transform,
158+
) -> Sequence[Artist]: ...
159+
147160
_T = TypeVar("_T", bound=Artist)
148161

149162
class HandlerRegularPolyCollection(HandlerNpointsYoffsets):

lib/matplotlib/tests/test_legend.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,28 @@ def test_linecollection_scaled_dashes():
625625
assert oh.get_linestyles()[0] == lh._dash_pattern
626626

627627

628+
def test_patch_collection_handler():
629+
fig, ax = plt.subplots()
630+
pc = mcollections.PatchCollection([
631+
plt.Circle((0, 0), radius=1, facecolor='red', edgecolor='green',
632+
linewidth=3, linestyle='--'),
633+
plt.Rectangle((0.5, 0.5), 1, 1),
634+
], match_original=True, label='my_collection')
635+
636+
ax.add_collection(pc)
637+
_, labels = ax.get_legend_handles_labels()
638+
assert len(labels) == 1
639+
assert labels[0] == 'my_collection'
640+
641+
leg = ax.legend()
642+
handles = leg.legend_handles
643+
assert mpl.colors.same_color(handles[0].get_facecolor(), 'red')
644+
assert mpl.colors.same_color(handles[0].get_edgecolor(), 'green')
645+
assert handles[0].get_linewidth() == 3
646+
np.testing.assert_allclose(handles[0].get_linestyle()[1],
647+
pc.get_linestyle()[0][1])
648+
649+
628650
def test_handler_numpoints():
629651
"""Test legend handler with numpoints <= 1."""
630652
# related to #6921 and PR #8478

0 commit comments

Comments
 (0)