我注意到我可以将自己的属性添加到matplotlib.axes.Axes()
和matplotlib.figure.Figure()
实例中。例如,
import matplotlib as mpl
f = mpl.figure.Figure()
a = f.add_subplot()
a.foo = 'bar'
实际上,我可能希望使用类似
之类的东西将底图实例添加到轴对象import mpl_toolkits.basemap as basemap
a.basemap = basemap.Basemap('mollweide', ax=a)
这样我就可以以更加面向对象的直观方式添加地理特征。这是这些物体的记录/可靠特征,还是偶然的?换句话说,我可以“安全地”使用它吗?
答案 0 :(得分:2)
根据此example,您可以为自定义图类添加任何新属性。但是对于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>
但是我的意见是你不需要设置axis类的m
属性。您必须根据自定义轴类中的底图调用所有函数,即在__init___
中(或使用set_basemap
之类的特殊方法)。