Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Rewrite of the entire legend documentation, including tidy ups of code and style to all things "legend". #2442

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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 28, 2014
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Review actions.
  • Loading branch information
pelson committed Jan 28, 2014
commit 59e7d13c9e2d80ca82ae123fac2de2eba636eb9e
3 changes: 2 additions & 1 deletion 3 doc/api/api_changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ original location:
`matplotlib.patches.Polygon` object.

* The legend handler interface has changed from a callable, to any object
which implements the ``legend_artists`` method. See
which implements the ``legend_artists`` method (a deprecation phase will
see this interface be maintained for v1.4). See
:ref:`plotting-guide-legend` for further details. Further legend changes
include:

Expand Down
18 changes: 11 additions & 7 deletions 18 doc/users/legend_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,27 @@ handles and their associated labels. This functionality is equivalent to::

The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` function returns
a list of handles/artists which exist on the Axes which can be used to
generate entries for the resulting legend.
generate entries for the resulting legend - it is worth noting however that
not all artists can be added to a legend, at which point a "proxy" will have
to be created (see :ref:`proxy_legend_handles` for further details).

For full control of what is being added to the legend, it is common to pass
the appropriate handles directly to :func:`legend`::

line2, = plt.plot([1,2,3], label='Line 2')
line1, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line1, line2])
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])

In some cases, it is not possible to set the label of the handle, so it is
possible to pass through the list of labels to :func:`legend`::

line2, = plt.plot([1,2,3], label='Line 2')
line1, = plt.plot([3,2,1], label='Line 1')
plt.legend([line1, line2], ['Custom label for line 1', 'Line 1'])
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend([line_up, line_down], ['Line Up', 'Line Down'])


.. _proxy_legend_handles:

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

Expand Down
3 changes: 2 additions & 1 deletion 3 lib/matplotlib/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
# ipython relies on interactive_bk being defined here
from matplotlib.rcsetup import interactive_bk

__all__ = ['backend']
__all__ = ['backend','show','draw_if_interactive',
'new_figure_manager', 'backend_version']

backend = matplotlib.get_backend() # validates, to match all_backends

Expand Down
15 changes: 14 additions & 1 deletion 15 lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@

from matplotlib import rcParams
from matplotlib.artist import Artist, allow_rasterization
from matplotlib.cbook import is_string_like, iterable, silent_list, safezip
from matplotlib.cbook import (is_string_like, iterable, silent_list, safezip,
warn_deprecated)
from matplotlib.font_manager import FontProperties
from matplotlib.lines import Line2D
from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch
Expand Down Expand Up @@ -621,6 +622,18 @@ def _init_legend_box(self, handles, labels):
height=height,
xdescent=0., ydescent=descent)
handleboxes.append(handlebox)

# Deprecate the old behaviour of accepting callable
# legend handlers in favour of the "legend_artist"
# interface.
if (not hasattr(handler, 'legend_artist') and
callable(handler)):
handler.legend_artist = handler.__call__
warn_deprecated('1.4',
('Legend handers must now implement a '
'"legend_artist" method rather than '
'being a callable.'))

# Create the artist for the legend which represents the
# original artist/handle.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add a if six.callable(handler) block to not break backwards compatibility + depreciation message?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see - so that we have a deprecation phase? I can have a quick look into that.

handle_list.append(handler.legend_artist(self, orig_handle,
Expand Down
29 changes: 29 additions & 0 deletions 29 lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
import numpy as np

from matplotlib.testing.decorators import image_comparison, cleanup
from matplotlib.cbook import MatplotlibDeprecationWarning
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patches as mpatches


@image_comparison(baseline_images=['legend_auto1'], remove_text=True)
Expand Down Expand Up @@ -130,6 +132,33 @@ def test_legend_label_loc_args(self):
deprecation.assert_called_with('1.4', self.deprecation_message)
Legend.assert_called_with(plt.gca(), [], ['hello world'], loc=1)

@cleanup
def test_old_legend_handler_interface(self):
# Check the deprecated warning is created and that the appropriate
# call to the legend handler is made.
class AnyObject(object):
pass

class AnyObjectHandler(object):
def __call__(self, legend, orig_handle, fontsize, handlebox):
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',
edgecolor='black', hatch='xx', lw=3,
transform=handlebox.get_transform())
handlebox.add_artist(patch)
return patch

with mock.patch('warnings.warn') as warn:
plt.legend([None], ['My first handler'],
handler_map={None: AnyObjectHandler()})

warn.assert_called_with(u'Legend handers must now implement a '
'"legend_artist" method rather than '
'being a callable.',
MatplotlibDeprecationWarning,
stacklevel=1)

@cleanup
def test_legend_handle_label_loc_args(self):
# Check the deprecated warning is created and that the appropriate
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.