5

I have a custom figure class and would like to ensure that all of the axes associated with it, whether created with subplots() or twinx(), etc. have custom behaviors.

Right now I accomplish this by binding new methods to each axis after it has been created, e.g. by using

import types

def my_ax_method(ax, test):
    print('{0} is doing something new as a {1}.'.format(ax, test))

class MyFigure(matplotlib.figure.Figure):
    def __init__(self, **kwargs):
        super(MyFigure, self).__init__(**kwargs)            
        axes_a = None
        axes_b = None
        axes_c = None

    def setup_axes(self, ax):    
        self.axes_a =  ax
        self.axes_b = self.axes_a.twinx()
        self.axes_c = self.axes_a.twiny()    
        self.axes_a.my_method = types.MethodType(my_ax_method, self.axes_a)
        self.axes_b.my_method = types.MethodType(my_ax_method, self.axes_b)
        self.axes_c.my_method = types.MethodType(my_ax_method, self.axes_c)

in something like

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

    fig.axes_a.my_method("probe of A")
    fig.axes_b.my_method("test of B")
    fig.axes_c.my_method("trial of C")

This seems like a fragile way to accomplish what I'm trying to do. Is there a better, more Pythonic way to go about this?

In particular, is there a way to ensure that all the Axes of my custom Figure class are of a specific class (as is done for figures themselves): a custom Axes class of my own that could have these methods as part of its definition?

Community
  • 1
  • 1
orome
  • 45,163
  • 57
  • 202
  • 418
  • This is an almost duplicate of http://stackoverflow.com/questions/27473683/can-i-get-the-axis-that-will-be-returned-by-pyplot-subplots-inside-the-constru?noredirect=1#comment43412613_27473683 – tacaswell Dec 23 '14 at 15:46
  • 3
    And the answer is still to overload `Figure.add_subplot`. Also take a look at how `AxesGrid` works. – tacaswell Dec 23 '14 at 15:51
  • 2
    @tcaswell: Only if (1) that is the only answer to this (which it might be) and (2) this is the only reason for doing asking that (which it isn't). – orome Dec 23 '14 at 15:51

0 Answers0