4

I'm using a custom figure class in a call to pyplot's subplot()

fig, ax = matplotlib.pyplot.subplots(FigureClass=MyFigure)

and would like to use the axis object(s), ax, normally returned by subplot(), in the constructor to the custom figure class. For example, I'd like to take that axis and twin it:

class MyFigure(matplotlib.figure.Figure):

    def __init__(self, *args, **kwargs):
        super(MyFigure, self).__init__(**kwargs)

        self.ax_one = self.method_that_gets_the_ax_returned_by_subplots()
        self.ax_two = self.ax_one.twinx()
        self.ax_three = self.ax_one.twinx()

but I can't find a way to get (what will be returned as) ax here. Using gca() results in a blank figure and an "extra" axis, for example; while using get_axes() results in errors (it's an empty list).

Is there a way to get the axis that will be returned by subplots inside the constructor for the figure it creates?

orome
  • 45,163
  • 57
  • 202
  • 418
  • 1
    No because the axes do not exist at the time the `Figure` objects gets created. I think you would be better putting that logic in the `add_subplot` function rather than the `__init__` function. A figure does not have to have an axes and can have _any_ number of axes, hard-coding that sort of thing in the `__init__` does not seem like a great idea. – tacaswell Dec 15 '14 at 02:12
  • @tcaswell: is there a figure method that `pyplot.subplots` calls to create and add the axes it returns? – orome Dec 15 '14 at 04:44
  • `add_subplot` You should go read the source (it is in pyplot.py), it will clarify a lot of these questions. – tacaswell Dec 15 '14 at 04:46
  • 1
    @tcaswell: I see that `add_subplot` is responsible for creating the axis object that's returned by `pyplot.subplots`, but I need that axis to start with. Where does it come from; and can I even safely override `add_subplot` without all kinds of side effects (given that this figure class always has only the axes defined above)? – orome Dec 15 '14 at 18:20

0 Answers0