根据example,您可以为自定义 Figure 类添加任何新属性。然而,对于 Axes 类,此类任务更为复杂。你必须制作自己的 Axes 类
from matplotlib.pyplot import figure, show
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
from mpl_toolkits.basemap import Basemap
# custom Figure class with foo property
class MyFigure(Figure):
def __init__(self, *args, **kwargs):
self.foo = kwargs.pop('foo', 'bar')
Figure.__init__(self, *args, **kwargs)
# custom Axes class
class MyAxes(Subplot):
def __init__(self, *args, **kwargs):
super(MyAxes, self).__init__(*args, **kwargs)
# add my axes
@staticmethod
def from_ax(ax=None, fig=None, *args, **kwargs):
if ax is None:
if fig is None: fig = figure(facecolor='w', edgecolor='w')
ax = MyAxes(fig, 1, 1, 1, *args, **kwargs)
fig.add_axes(ax)
return ax
# test run
# custom figure
fig = figure(FigureClass=MyFigure, foo='foo')
print (type(fig), fig.foo)
# add to figure custom axes
ax = MyAxes.from_ax(fig=fig)
print (type(fig.gca()))
# create Basemap instance and store it to 'm' property
ax.m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49,
projection='lcc', lat_1=33, lat_2=45, lon_0=-95, resolution='c')
ax.m.drawcoastlines(linewidth=.25)
ax.m.drawcountries(linewidth=.25)
ax.m.fillcontinents(color='coral', lake_color='aqua')
print (ax.m)
show()
输出:
<class '__main__.MyFigure'> foo
<class '__main__.MyAxes'>
<mpl_toolkits.basemap.Basemap object at 0x107fc0358>
但是我的意见是,您不需要创建轴类的 m 属性。您必须根据自定义轴类中的底图调用所有函数,即在__init___ 中(或制作像set_basemap 这样的特殊方法)。