Skip to content

Add fig.add_artist method #11234

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
Jul 19, 2018
Merged
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
18 changes: 18 additions & 0 deletions doc/users/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ specify a number that is close (i.e. ``ax.title.set_position(0.5, 1.01)``)
and the title will not be moved via this algorithm.



New convenience methods for GridSpec
------------------------------------

Expand All @@ -210,6 +211,23 @@ now call `.Figure.add_gridspec` and for the latter `.SubplotSpec.subgridspec`.
fig.add_subplot(gssub[0, i])


Figure has an `~.figure.Figure.add_artist` method
-------------------------------------------------

A method `~.figure.Figure.add_artist` has been added to the
:class:`~.figure.Figure` class, which allows artists to be added directly
to a figure. E.g.

::

circ = plt.Circle((.7, .5), .05)
fig.add_artist(circ)

In case the added artist has no transform set previously, it will be set to
the figure transform (``fig.transFigure``).
This new method may be useful for adding artists to figures without axes or to
easily position static elements in figure coordinates.




Expand Down
36 changes: 36 additions & 0 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,42 @@ def fixlist(args):
key = fixlist(args), fixitems(kwargs.items())
return key

def add_artist(self, artist, clip=False):
"""
Add any :class:`~matplotlib.artist.Artist` to the figure.

Usually artists are added to axes objects using
:meth:`matplotlib.axes.Axes.add_artist`, but use this method in the
rare cases that adding directly to the figure is necessary.

Parameters
----------
artist : `~matplotlib.artist.Artist`
The artist to add to the figure. If the added artist has no
transform previously set, its transform will be set to
``figure.transFigure``.
clip : bool, optional, default ``False``
An optional parameter ``clip`` determines whether the added artist
should be clipped by the figure patch. Default is *False*,
i.e. no clipping.

Returns
-------
artist : The added `~matplotlib.artist.Artist`
"""
artist.set_figure(self)
self.artists.append(artist)
artist._remove_method = self.artists.remove

if not artist.is_transform_set():
artist.set_transform(self.transFigure)

if clip:
artist.set_clip_path(self.patch)
Copy link
Member

Choose a reason for hiding this comment

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

This should always be passed, unless you can guarantee that the clip path was always False, or it should default to None if you really don't want to change the existing setting. That is, assuming it has an effect (re. @efiring's comment).

Copy link
Member

Choose a reason for hiding this comment

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

Actually, I think I misread this, and thought clip was being passed down. Since it isn't, this doesn't really matter.


self.stale = True
return artist

@docstring.dedent_interpd
def add_axes(self, *args, **kwargs):
"""
Expand Down
28 changes: 27 additions & 1 deletion lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import warnings

from matplotlib import rcParams
from matplotlib.testing.decorators import image_comparison
from matplotlib.testing.decorators import image_comparison, check_figures_equal
from matplotlib.axes import Axes
from matplotlib.ticker import AutoMinorLocator, FixedFormatter
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -381,6 +381,32 @@ def test_warn_cl_plus_tl():
assert not(fig.get_constrained_layout())


@check_figures_equal(extensions=["png", "pdf", "svg"])
def test_add_artist(fig_test, fig_ref):
fig_test.set_dpi(100)
fig_ref.set_dpi(100)

ax = fig_test.subplots()
l1 = plt.Line2D([.2, .7], [.7, .7])
l2 = plt.Line2D([.2, .7], [.8, .8])
r1 = plt.Circle((20, 20), 100, transform=None)
r2 = plt.Circle((.7, .5), .05)
r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,
facecolor='crimson')
for a in [l1, l2, r1, r2, r3]:
fig_test.add_artist(a)
l2.remove()

ax2 = fig_ref.subplots()
l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure)
r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20)
r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure)
r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,
facecolor='crimson', clip_on=False, zorder=20)
for a in [l1, r1, r2, r3]:
ax2.add_artist(a)


@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python 3.6+")
@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
def test_fspath(fmt, tmpdir):
Expand Down