2012-05-10 9 views
1

私はmatplotlibを使って宇宙船の軌道の2Dビューをプロットしています。この軌道上で、特定のイベントを特定してマークし、これらのイベントと対応する日付を凡例に記載します。フィギュアをファイルに保存する前に、自分の軌道プロットをオートズームして、プロットの上に凡例を直接印刷します。私がしたいのは、オートスケーリングの後に、何とか私の凡例の幅を見つけてから、プロットの右側にある凡例のための「部屋を作る」ために私のxaxisを拡張することです。概念的には、このようなもの。matplotlibをオートスケールする凡例のための空間を作るための軸

# ... code that generates my plot up here, then: 
ax.autoscale_view() 
leg = ax.get_legend() 
leg_width = # Somehow get the width of legend in units that I can use to modify my axes 
xlims = ax.get_xlim() 
ax.set_xlim([xlims[0], xlims[1] + leg_width]) 
fig.savefig('myplot.ps',format='ps') 

私がいる主な問題はax.set_xlim()は、ウィンドウのピクセル単位でleg.get_window_extentレポートに対し、「データ」とは、特定の値を、(と思う)かかること、そして唯一のキャンバス後に描かれていてもということですので、私はよ私は上記と同様に使用できる方法で伝説の「幅」をどのように得ることができるかわからない。

答えて

0

実際の凡例の位置を取得するには、Figureを一度保存​​してから、transData.inverted()を使用してスクリーン座標をデータ座標に変換します。

import pylab as pl 
ax = pl.subplot(111) 
pl.plot(pl.randn(1000), pl.randn(1000), label="ok") 
leg = pl.legend() 

pl.savefig("test.png") # save once to get the legend location 

x,y,w,h = leg.get_window_extent().bounds 

# transform from screen coordinate to screen coordinate 
tmp1, tmp2 = ax.transData.inverted().transform([0, w]) 
print abs(tmp1-tmp2) # this is the with of legend in data coordinate 

pl.savefig("test.png") 
関連する問題