8000 Merge pull request #27731 from story645/legend-guide · matplotlib/matplotlib@4ef891e · GitHub
[go: up one dir, main page]

Skip to content

Commit 4ef891e

Browse files
authored
Merge pull request #27731 from story645/legend-guide
DOC: Create explict rename legend entry section in guide
2 parents 968e554 + 47c7f7d commit 4ef891e

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

galleries/users_explain/axes/legend_guide.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,29 @@
5959
line_down, = ax.plot([3, 2, 1], label='Line 1')
6060
ax.legend(handles=[line_up, line_down])
6161
62-
In the rare case where the labels cannot directly be set on the handles, they
63-
can also be directly passed to :func:`legend`::
62+
Renaming legend entries
63+
-----------------------
64+
65+
When the labels cannot directly be set on the handles, they can be directly passed to
66+
`.Axes.legend`::
6467
6568
fig, ax = plt.subplots()
6669
line_up, = ax.plot([1, 2, 3], label='Line 2')
6770
line_down, = ax.plot([3, 2, 1], label='Line 1')
6871
ax.legend([line_up, line_down], ['Line Up', 'Line Down'])
6972
7073
74+
If the handles are not directly accessible, for example when using some
75+
`Third-party packages <https://matplotlib.org/mpl-third-party/>`_, they can be accessed
76+
via `.Axes.get_legend_handles_and_labels`. Here we use a dictionary to rename existing
77+
labels::
78+
79+
my_map = {'Line Up':'Up', 'Line Down':'Down'}
80+
81+
handles, labels = ax.get_legend_handles_labels()
82+
ax.legend(handles, [my_map[l] for l in labels])
83+
84+
7185
.. _proxy_legend_handles:
7286
7387
Creating artists specifically for adding to the legend (aka. Proxy artists)

0 commit comments

Comments
 (0)
0