3

I'm trying to add some custom behaviors and properties to my figures, but I'm having trouble deciding on an effective (and Pythonic) approach.

My first impulse is to simply subclass matplotlib.figure.Figure but I can't figure out how to accomplish this: I generally create new figures and start my plotting with something like

fig, ax = matplotlib.pyplot.subplots()

and I can't figure out how this would work with a custom Figure subclass.

How can I subclass Figure in a way that still lets me use pyplot methods like the one above? Is subclassing even the right way to get custom behaviors associated with a figure? Are the better approaches?

orome
  • 45,163
  • 57
  • 202
  • 418

1 Answers1

6

subplots takes additional keyword arguments that are passed directly to figures(), one of which is the class used to create the figures.

class MyFigure(Figure):
    pass

fig, ax = matplotlib.pyplot.subplots(FigureClass=MyFigure)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I'm a bit embarrassed (and relieved (and again impressed with matplotlib's architecture)) that it's so simple. Is there a way to also ensure that the axes returned is of a particular class? – orome Dec 14 '14 at 17:05
  • I'm not sure. The figure was relatively easy to figure out (`fig_kw` is a documented argument to `subplots`. I don't see anything obvious that gets passed to, or via, `figures` that specifies a class to use in place of `Axes`. It might be something you configure in your `Figure` subclass via `add_axes`. – chepner Dec 14 '14 at 18:08
  • 1
    [Follow-on question](http://stackoverflow.com/q/27611248/656912) about ensuring all the `Axes` for a custom figure are of a custom class. – orome Dec 22 '14 at 22:28