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

Skip to content

Commit 8cd780f

Browse files
authored
Merge pull request #15898 from DanHickstein/legend_textcolor
New textcolor kwarg for legend
2 parents 05e17af + 73d28ac commit 8cd780f

File tree

3 files changed

+116
-2
lines changed

3 files changed

+116
-2
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
Text color for legend labels
2+
----------------------------
3+
4+
The text color of legend labels can now be set by passing a parameter
5+
``labelcolor`` to `~.axes.Axes.legend`. The ``labelcolor`` keyword can be:
6+
7+
* A single color (either a string or RGBA tuple), which adjusts the text color
8+
of all the labels.
9+
* A list or tuple, allowing the text color of each label to be set
10+
individually.
11+
* ``linecolor``, which sets the text color of each label to match the
12+
corresponding line color.
13+
* ``markerfacecolor``, which sets the text color of each label to match the
14+
corresponding marker face color.
15+
* ``markeredgecolor``, which sets the text color of each label to match the
16+
corresponding marker edge color.

lib/matplotlib/legend.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,14 @@
2121
information.
2222
"""
2323

24+
import itertools
2425
import logging
2526
import time
2627

2728
import numpy as np
2829

2930
import matplotlib as mpl
30-
from matplotlib import cbook, docstring
31+
from matplotlib import cbook, docstring, colors
3132
from matplotlib.artist import Artist, allow_rasterization
3233
from matplotlib.cbook import silent_list
3334
from matplotlib.font_manager import FontProperties
@@ -172,6 +173,12 @@ def _update_bbox_to_anchor(self, loc_in_canvas):
172173
absolute font size in points. String values are relative to the current
173174
default font size. This argument is only used if *prop* is not specified.
174175
176+
labelcolor : str or list
177+
Sets the color of the text in the legend. Can be a valid color string
178+
(for example, 'red'), or a list of color strings. The labelcolor can
179+
also be made to match the color of the line or marker using 'linecolor',
180+
'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
181+
175182
numpoints : int, default: :rc:`legend.numpoints`
176183
The number of marker points in the legend when creating a legend
177184
entry for a `.Line2D` (line).
@@ -293,7 +300,8 @@ def __init__(self, parent, handles, labels,
293300
scatterpoints=None, # number of scatter points
294301
scatteryoffsets=None,
295302
prop=None, # properties for the legend texts
296-
fontsize=None, # keyword to set font size directly
303+
fontsize=None, # keyword to set font size directly
304+
labelcolor=None, # keyword to set the text color
297305

298306
# spacing & pad defined as a fraction of the font-size
299307
borderpad=None, # the whitespace inside the legend border
@@ -505,6 +513,36 @@ def __init__(self, parent, handles, labels,
505513
self.set_title(title, prop=tprop)
506514
self._draggable = None
507515

516+
# set the text color
517+
518+
color_getters = { # getter function depends on line or patch
519+
'linecolor': ['get_color', 'get_facecolor'],
520+
'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
521+
'mfc': ['get_markerfacecolor', 'get_facecolor'],
522+
'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
523+
'mec': ['get_markeredgecolor', 'get_edgecolor'],
524+
}
525+
if labelcolor is None:
526+
pass
527+
elif isinstance(labelcolor, str) and labelcolor in color_getters:
528+
getter_names = color_getters[labelcolor]
529+
for handle, text in zip(self.legendHandles, self.texts):
530+
for getter_name in getter_names:
531+
try:
532+
color = getattr(handle, getter_name)()
533+
text.set_color(color)
534+
break
535+
except AttributeError:
536+
pass
537+
elif np.iterable(labelcolor):
538+
for text, color in zip(self.texts,
539+
itertools.cycle(
540+
colors.to_rgba_array(labelcolor))):
541+
text.set_color(color)
542+
else:
543+
raise ValueError("Invalid argument for labelcolor : %s" %
544+
str(labelcolor))
545+
508546
def _set_artist_props(self, a):
509547
"""
510548
Set the boilerplate props for artists added to axes.

lib/matplotlib/tests/test_legend.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,66 @@ def test_legend_title_fontsize():
534534
assert leg.get_title().get_fontsize() == 22
535535

536536

537+
def test_legend_labelcolor_single():
538+
# test labelcolor for a single color
539+
fig, ax = plt.subplots()
540+
ax.plot(np.arange(10), np.arange(10)*1, label='#1')
541+
ax.plot(np.arange(10), np.arange(10)*2, label='#2')
542+
ax.plot(np.arange(10), np.arange(10)*3, label='#3')
543+
544+
leg = ax.legend(labelcolor='red')
545+
for text in leg.get_texts():
546+
assert mpl.colors.same_color(text.get_color(), 'red')
547+
548+
549+
def test_legend_labelcolor_list():
550+
# test labelcolor for a list of colors
551+
fig, ax = plt.subplots()
552+
ax.plot(np.arange(10), np.arange(10)*1, label='#1')
553+
ax.plot(np.arange(10), np.arange(10)*2, label='#2')
554+
ax.plot(np.arange(10), np.arange(10)*3, label='#3')
555+
556+
leg = ax.legend(labelcolor=['r', 'g', 'b'])
557+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
558+
assert mpl.colors.same_color(text.get_color(), color)
559+
560+
561+
def test_legend_labelcolor_linecolor():
562+
# test the labelcolor for labelcolor='linecolor'
563+
fig, ax = plt.subplots()
564+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', color='r')
565+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', color='g')
566+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', color='b')
567+
568+
leg = ax.legend(labelcolor='linecolor')
569+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
570+
assert mpl.colors.same_color(text.get_color(), color)
571+
572+
573+
def test_legend_labelcolor_markeredgecolor():
574+
# test the labelcolor for labelcolor='markeredgecolor'
575+
fig, ax = plt.subplots()
576+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')
577+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')
578+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')
579+
580+
leg = ax.legend(labelcolor='markeredgecolor')
581+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
582+
assert mpl.colors.same_color(text.get_color(), color)
583+
584+
585+
def test_legend_labelcolor_markerfacecolor():
586+
# test the labelcolor for labelcolor='markerfacecolor'
587+
fig, ax = plt.subplots()
588+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')
589+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')
590+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')
591+
592+
leg = ax.legend(labelcolor='markerfacecolor')
593+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
594+
assert mpl.colors.same_color(text.get_color(), color)
595+
596+
537597
def test_get_set_draggable():
538598
legend = plt.legend()
539599
assert not legend.get_draggable()

0 commit comments

Comments
 (0)