2017-05-01 8 views
4

matplotlib.axes.Axes()matplotlib.figure.Figure()インスタンスに独自の属性を追加できることに気付きました。例えば、実用的な面ではmatplotlibにカスタム属性を追加するFigureとAxesのインスタンス:不注意?

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) 

のようなものを使用してオブジェクト指向性のある、直感的な方法。これはこれらのオブジェクトの文書化された/信頼できる機能ですか、それとも偶然ですか?言い換えれば、私はこれを「安全に」使用できますか?

答えて

2

このexampleによれば、カスタムFigureクラスの新しいプロパティを追加できます。しかし、Axesクラスの場合、そのようなタスクはより複雑です。私の意見はあなたが軸クラスのmプロパティを作成する必要がないということであるしかし

<class '__main__.MyFigure'> foo 
<class '__main__.MyAxes'> 
<mpl_toolkits.basemap.Basemap object at 0x107fc0358> 

enter image description here

:あなたは自分の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() 

出力を行う必要があります。すべての関数をカスタム軸クラスのベースマップ、つまり__init___(またはset_basemapのような特別なメソッドを作成)で呼び出す必要があります。

+1

ありがとう、これは非常に役に立ちました。私は通常、作成する図形の種類に対して便利な自動書式設定関数を持っています。代わりにその定義を 'Figure'サブクラスのメソッド(もっとクリーンなもの)にします。そして、あなたが正しいです、おそらく軸のサブクラス化を気にせず、座標変換を手動で行うだけです。 'cartopy'(オブジェクト指向/直感的です)を使用しますが、残念ながら' basemap'はやはり機能が豊富です(例えば 'cartopy'の経度/緯度ラベルはほとんど使用できません) 。 –

関連する問題