Skip to content

Commit 81a9464

Browse files
committed
Simplify legend handler for PolyCollections.
Closes #20258. Alternative to #20260.
1 parent 69b51f1 commit 81a9464

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

lib/matplotlib/legend_handler.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -734,32 +734,30 @@ class HandlerPolyCollection(HandlerBase):
734734
"""
735735
def _update_prop(self, legend_handle, orig_handle):
736736
def first_color(colors):
737-
if colors is None:
738-
return None
739-
colors = mcolors.to_rgba_array(colors)
740-
if len(colors):
741-
return colors[0]
742-
else:
743-
return "none"
737+
if colors.size == 0:
738+
return (0, 0, 0, 0)
739+
return tuple(colors[0])
744740

745741
def get_first(prop_array):
746742
if len(prop_array):
747743
return prop_array[0]
748744
else:
749745
return None
750-
edgecolor = getattr(orig_handle, '_original_edgecolor',
751-
orig_handle.get_edgecolor())
752-
legend_handle.set_edgecolor(first_color(edgecolor))
753-
facecolor = getattr(orig_handle, '_original_facecolor',
754-
orig_handle.get_facecolor())
755-
legend_handle.set_facecolor(first_color(facecolor))
756-
legend_handle.set_fill(orig_handle.get_fill())
757-
legend_handle.set_hatch(orig_handle.get_hatch())
746+
747+
# orig_handle is a PolyCollection and legend_handle is a Patch.
748+
# Directly set Patch color attributes (must be RGBA tuples).
749+
legend_handle._facecolor = first_color(orig_handle.get_facecolor())
750+
legend_handle._edgecolor = first_color(orig_handle.get_edgecolor())
751+
legend_handle._fill = orig_handle.get_fill()
752+
legend_handle._hatch = orig_handle.get_hatch()
753+
# Hatch color is anomalous in having no getters and setters.
754+
legend_handle._hatch_color = orig_handle._hatch_color
755+
# Setters are fine for the remaining attributes.
758756
legend_handle.set_linewidth(get_first(orig_handle.get_linewidths()))
759757
legend_handle.set_linestyle(get_first(orig_handle.get_linestyles()))
760758
legend_handle.set_transform(get_first(orig_handle.get_transforms()))
761759
legend_handle.set_figure(orig_handle.get_figure())
762-
legend_handle.set_alpha(orig_handle.get_alpha())
760+
# Alpha is already taken into account by the color attributes.
763761

764762
def create_artists(self, legend, orig_handle,
765763
xdescent, ydescent, width, height, fontsize, trans):

0 commit comments

Comments
 (0)