2011-12-21 69 views
4

如何使用figtext()添加文本時展開(垂直)圖形/繪圖/圖形?長線自動展開畫布

的代碼是這樣的:

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

所以我需要的圖像自動擴展以適應情節,x軸標籤和figtext。目前文字first line\nsecond line\nthird line是重疊的x軸標籤。

+0

我不認爲有一種實現這一點的自動方式。通常,你必須自己調整邊距。 – 2011-12-21 09:30:04

+1

當使用'xlabel'添加文本時,可以通過callyng'plt.tight_layout()'動態擴展畫布,但不幸的是這對'plt.figtext()'不起作用。 – 2011-12-21 10:11:50

+0

還有一些解決方法 - 向xlabel添加一些換行符,但我不喜歡它。 – 2011-12-21 10:13:34

回答

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

但添加文本時,將其調整爲: enter image description here

hspace插曲參數可能需要調整,這取決於大小的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

謝謝你的答案。 – 2011-12-21 18:22:48