How do I ensure that my matplotlib axes are of a custom class?
Asked Answered
E

0

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?

Exosmosis answered 22/12, 2014 at 22:14 Comment(3)
This is an almost duplicate of #27474183Illuminati
And the answer is still to overload Figure.add_subplot. Also take a look at how AxesGrid works.Illuminati
@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).Exosmosis

© 2022 - 2024 — McMap. All rights reserved.