问题
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?
来源:https://stackoverflow.com/questions/27611248/how-do-i-ensure-that-my-matplotlib-axes-are-of-a-custom-class