编程语言
首页 > 编程语言> > python – 向matplotlib添加自定义属性图和轴实例:不明智?

python – 向matplotlib添加自定义属性图和轴实例:不明智?

作者:互联网

我注意到我可以将自己的属性添加到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)

这样我就可以以更加面向对象的直观方式添加地理特征.这是这些物体的记录/可靠特征,还是偶然的?换句话说,我可以“安全地”使用它吗?

解决方法:

根据这个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>

enter image description here

但是我的意见是你不需要创建axis类的m属性.您必须根据自定义轴类中的底图调用所有函数,即在__init___中(或使用set_basemap等特殊方法).

标签:python,python-3-x,matplotlib,matplotlib-basemap
来源: https://codeday.me/bug/20190701/1350308.html