How do I subclass matplotlib's figure class?
Asked Answered
P

1

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?

Peek answered 14/12, 2014 at 15:20 Comment(0)
C
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)
Confidence answered 14/12, 2014 at 15:43 Comment(3)
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?Peek
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.Confidence
Follow-on question about ensuring all the Axes for a custom figure are of a custom class.Peek

© 2022 - 2024 — McMap. All rights reserved.