Support placing legend symbols next to axis labels by alexhartl · Pull Request #16005 · matplotlib/matplotlib · GitHub
Skip to content
Draft
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions doc/api/axes_api.rst
7 changes: 7 additions & 0 deletions doc/users/next_whats_new/2019-12-22-axis-label-legend.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Support for axis label legends
------------------------------

Legends can now be placed next to axis labels, enabling more
space-efficient and intuitive ``twinx()`` plots. Such legends are created
using ``plt.xlabel_legend()`` and ``plt.ylabel_legend()``, which each
accept one artist handle as understood by ``plt.legend()``.
45 changes: 45 additions & 0 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,21 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
self.xaxis.labelpad = labelpad
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)

def set_xlabel_legend(self, handle, **kwargs):
"""
Place a legend next to the axis label.

Parameters
----------
handle: `.Artist`
An artist (e.g. lines, patches) to be shown as legend.

**kwargs: `.LegendConfig` properties
Additional properties to control legend appearance.
"""
label = self.xaxis.get_label()
label.set_legend_handle(handle, **kwargs)

def get_ylabel(self):
"""
Get the ylabel text string.
Expand Down Expand Up @@ -248,6 +263,36 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
self.yaxis.labelpad = labelpad
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)

def set_ylabel_legend(self, handle, **kwargs):
"""
Place a legend next to the axis label.

Parameters
----------
handle: `.Artist`
An artist (e.g. lines, patches) to be shown as legend.

**kwargs: `.LegendConfig` properties
Additional properties to control legend appearance.

Examples
--------
Plot two lines on different axes with legends placed next to the
axis labels::

artist, = plt.plot([0, 1, 2], [0, 1, 2], "b-")
plt.ylabel('Density')
plt.ylabel_legend(artist)

plt.twinx()
artist, = plt.plot([0, 1, 2], [0, 3, 2], "r-")
plt.ylabel('Temperature')
plt.ylabel_legend(artist)
plt.show()
"""
label = self.yaxis.get_label()
label.set_legend_handle(handle, **kwargs)

def get_legend_handles_labels(self, legend_handler_map=None):
"""
Return handles and labels for legend
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/axis.py
Loading