2011-12-21 10 views
4

figtext()を使ってテキストを追加するとき、figure/plot/figureを(垂直に)展開する方法は?長い線のために自動的にキャンバスを展開する

コードはこのようなものです:

plt.figtext(0.5 ,0, u'first line\nsecond line\nthird line', ha='center') 

だから私は、自動的にx軸ラベルとfigtext、プロットに合うように展開された画像にする必要があります。現在、テキストfirst line\nsecond line\nthird lineは、x軸ラベルと重複しています。

+0

私はこれを達成するための自動方法がないと思います。通常、マージンは自分で調整する必要があります。 –

+1

'xlabel'を使ってテキストを追加するとき、' plt.tight_layout() 'をcallyngで動的に展開することは可能ですが、残念なことに' plt.figtext() 'ではこれが機能しません。 –

+0

いくつかの回避策があります - xlabelにいくつかの改行を追加しますが、私はそれを気に入らないのです。 –

答えて

1

考えられる多くの疑問があるため、これを行うための自動方法はありません。サブプロットを調整するときに図に属するArtistsを考慮する必要がありますか?

これは今のところ手動で行うことができます。テキストを含むボックスのサイズを知る必要があります。図形のテキストが下部にあることを知っているので、このテキストボックスの上部は図の「新しい」底部と見なす必要があります。

tight_layoutモジュールが提供するget_rendererを使用して、テキストサイズに関する適切な情報をdpiで取得しました。

from matplotlib.tight_layout import get_renderer 
import matplotlib.pyplot as plt 

FONTSIZE=20 

# set up example plots 
fig = plt.figure() 

ax1 = fig.add_subplot(211) 
ax1.plot(range(10,1,-1)) 
ax1.set_title('ax1',fontsize=FONTSIZE) 
ax1.set_xlabel('X axis',fontsize=FONTSIZE) 
ax1.set_ylabel('Y axis',fontsize=FONTSIZE) 

ax2 = fig.add_subplot(212) 
ax2.plot(range(1,10,1)) 
ax2.set_title('ax1',fontsize=FONTSIZE) 
ax2.set_xlabel('X axis',fontsize=FONTSIZE) 
ax2.set_ylabel('Y axis',fontsize=FONTSIZE) 

# tighten things up in advance 
print "Subplots 'bottom' before tight_layout: ",fig.subplotpars.bottom 
plt.tight_layout() 
print "Subplots 'bottom' after tight_layout: ",fig.subplotpars.bottom 
fig.savefig('noFigText.png') 

# add and deal with text 
bigFigText = plt.figtext(0.5 ,0.05, 
         u'first line\nsecond line\nthird line', 
         ha='center') 
# textLimitsDpi is a 2x2 array correspoinding to [[x0,y0],[x1,y1]] 
textLimitsDpi = bigFigText.get_window_extent(renderer=get_renderer(fig), 
            dpi=fig.get_dpi()).get_points() 

# we really just need y1 
textHeightFig = fig.transFigure.inverted().transform((0,textLimitsDpi[1,1]))[1] 

# make adjustment to bottom 
fig.subplots_adjust(bottom=fig.subplotpars.bottom+textHeightFig) 

print "Subplots 'bottom' after figtext: ",fig.subplotpars.bottom 
fig.savefig('withFigText.png') 
plt.show() 

結果の出力である:

tight_layout前サブプロット '底':0.1

tight_layout後サブプロット '底':0.109166666667

この例では、基本的な考え方を示しています

figtextの後のサブプロット 'ボトム':0.259166666667

アウトテキストとの緊密なレイアウト図は次のとおりです。 enter image description here

しかし、テキストを追加するとき、それがに調整​​されている:hspaceサブプロットのパラメータは、あなたのサイズに応じて、調整する必要があるかもしれません enter image description here

figtextテキストボックス。テキストを垂直方向に(0.05)移動し、サブプロットのパラメータのボトムを調整するためにテキストボックスのy1を使用していたので、この調整が考慮されています。

理想的には、y範囲の新しい下限(つまり0ではなく)を考慮してtight_layoutで行われた作業をやり直すことをお勧めしますが、以下はほとんどのフォントサイズ(8-48)でうまく動作するハックですfigtextテキストボックス:

# make adjustment to bottom 
top = fig.subplotpars.top 
bottom = fig.subplotpars.bottom 
newHspace = (fig.subplotpars.hspace 
      *(top-bottom) 
      /(top-bottom-textHeightFig)) 
fig.subplots_adjust(bottom=bottom+textHeightFig, 
        hspace=newHspace) 
+0

ありがとう、答えのために。 –

関連する問題