Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ffdbe6e

Browse files
committed
ENH/WIP: first draft of ensure_ax
Decorator for making user functions using the suggested signature work with the state machine to plot the the implicit currently active Axes.
1 parent 5630a97 commit ffdbe6e

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

lib/matplotlib/pyplot.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
import types
2626

2727
from cycler import cycler
28+
29+
from functools import wraps
30+
2831
import matplotlib
2932
import matplotlib.colorbar
3033
from matplotlib import style
@@ -190,6 +193,74 @@ def uninstall_repl_displayhook():
190193
draw_all = _pylab_helpers.Gcf.draw_all
191194

192195

196+
def ensure_ax(func):
197+
"""Decorator to ensure that the function gets an `Axes` object.
198+
199+
200+
The intent of this decorator is to simplify the writing of helper
201+
plotting functions that are useful for both interactive and
202+
programmatic usage.
203+
204+
The encouraged signature for third-party and user functions ::
205+
206+
def my_function(ax, data, style)
207+
208+
explicitly expects an Axes object as input rather than using
209+
plt.gca() or creating axes with in the function body. This
210+
allows for great flexibility, but some find it verbose for
211+
interactive use. This decorator allows the Axes input to be
212+
omitted in which case `plt.gca()` is passed into the function.
213+
Thus ::
214+
215+
wrapped = ensure_ax(my_function)
216+
217+
can be called as any of ::
218+
219+
wrapped(data, style)
220+
wrapped(ax, data, style)
221+
wrapped(data, style, ax=plt.gca())
222+
223+
224+
"""
225+
@wraps(func)
226+
def inner(*args, **kwargs):
227+
if 'ax' in kwargs:
228+
ax = kwargs.pop('ax', None)
229+
elif len(args) > 0 and isinstance(args[0], Axes):
230+
ax = args[0]
231+
args = args[1:]
232+
else:
233+
ax = gca()
234+
return func(ax, *args, **kwargs)
235+
return inner
236+
237+
238+
def ensure_ax_meth(func):
239+
"""
240+
The same as ensure axes, but for class methods ::
241+
242+
class foo(object):
243+
@ensure_ax_meth
244+
def my_function(self, ax, style):
245+
246+
will allow you to call your objects plotting methods with
247+
out explicitly passing in an `Axes` object.
248+
"""
249+
@wraps(func)
250+
def inner(*args, **kwargs):
251+
s = args[0]
252+
args = args[1:]
253+
if 'ax' in kwargs:
254+
ax = kwargs.pop('ax', None)
255+
elif len(args) > 1 and isinstance(args[0], Axes):
256+
ax = args[0]
257+
args = args[1:]
258+
else:
259+
ax = gca()
260+
return func(s, ax, *args, **kwargs)
261+
return inner
262+
263+
193264
@docstring.copy_dedent(Artist.findobj)
194265
def findobj(o=None, match=None, include_self=True):
195266
if o is None:

0 commit comments

Comments
 (0)