Skip to content

DOC: Create explicit rename legend entry section in guide #27731

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 2, 2024
Merged
Changes from all commits
Commits
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
18 changes: 16 additions & 2 deletions galleries/users_explain/axes/legend_guide.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,29 @@
line_down, = ax.plot([3, 2, 1], label='Line 1')
ax.legend(handles=[line_up, line_down])

In the rare case where the labels cannot directly be set on the handles, they
can also be directly passed to :func:`legend`::
Renaming legend entries
-----------------------

When the labels cannot directly be set on the handles, they can be directly passed to
`.Axes.legend`::

fig, ax = plt.subplots()
line_up, = ax.plot([1, 2, 3], label='Line 2')
line_down, = ax.plot([3, 2, 1], label='Line 1')
ax.legend([line_up, line_down], ['Line Up', 'Line Down'])


If the handles are not directly accessible, for example when using some
`Third-party packages <https://matplotlib.org/mpl-third-party/>`_, they can be accessed
via `.Axes.get_legend_handles_and_labels`. Here we use a dictionary to rename existing
labels::

my_map = {'Line Up':'Up', 'Line Down':'Down'}

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, [my_map[l] for l in labels])


.. _proxy_legend_handles:

Creating artists specifically for adding to the legend (aka. Proxy artists)
Expand Down