Can I get the axis that will be returned by `pyplot.subplots` inside the constructor for the figure it creates?
Asked Answered
R

0

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?

Regressive answered 14/12, 2014 at 20:24 Comment(4)
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.Dornick
@tcaswell: is there a figure method that pyplot.subplots calls to create and add the axes it returns?Regressive
add_subplot You should go read the source (it is in pyplot.py), it will clarify a lot of these questions.Dornick
@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)?Regressive

© 2022 - 2024 — McMap. All rights reserved.