|
25 | 25 | import types
|
26 | 26 |
|
27 | 27 | from cycler import cycler
|
| 28 | + |
| 29 | +from functools import wraps |
| 30 | + |
28 | 31 | import matplotlib
|
29 | 32 | import matplotlib.colorbar
|
30 | 33 | from matplotlib import style
|
@@ -190,6 +193,74 @@ def uninstall_repl_displayhook():
|
190 | 193 | draw_all = _pylab_helpers.Gcf.draw_all
|
191 | 194 |
|
192 | 195 |
|
| 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 | + |
193 | 264 | @docstring.copy_dedent(Artist.findobj)
|
194 | 265 | def findobj(o=None, match=None, include_self=True):
|
195 | 266 | if o is None:
|
|
0 commit comments