2011-09-23 27 views
60

我已經開始與matplot和管理的一些基本情節,但現在我覺得很難發現如何做一些東西,我現在:(Matplotlib - 全球傳說和標題一旁的次要情節

我實際的問題是如何需要將一個全局標題和全局圖例放在一個帶有子圖的圖上

我正在做2x3子圖,其中有很多不同顏色的圖形(大約200)。像

def style(i, total): 
    return dict(color=jet(i/total), 
       linestyle=["-", "--", "-.", ":"][i%4], 
       marker=["+", "*", "1", "2", "3", "4", "s"][i%7]) 

fig=plt.figure() 
p0=fig.add_subplot(321) 
for i, y in enumerate(data): 
    p0.plot(x, trans0(y), "-", label=i, **style(i, total)) 
# and more subplots with other transN functions 

(對此有何看法?:))每個子圖具有相同的風格功能。

現在我試圖讓所有的小插圖的全球標題,也是一個解釋所有風格的全球傳奇。此外,我需要使字體很小,以適應所有200種風格(我不需要完全獨特的風格,但至少有一些嘗試)

有人可以幫我解決這個任務嗎?

+1

全球標題:http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html –

回答

112

全球標題:在matplotlib的新版本可以使用Figure.suptitle()

from pylab import * 
fig = gcf() 
fig.suptitle("Title centered above all subplots", fontsize=14) 
+33

對於那些進口這樣的:'import matplotlib.pyplot as plt',該命令可以簡單地輸入爲'plt.figure(); plt.suptitle('標題集中在所有子圖上面'); plt.subplot(231); plt.plot(data [:,0],data [:,1]);'etc ... –

+0

謝謝。這應該是實際選定的答案。 – gustafbstrom

7

對於圖例標籤可以使用類似下面的內容。圖例標籤是保存的繪圖線。 modFreq是繪製線對應的實際標籤的名稱。然後第三個參數是圖例的位置。最後,你可以傳入任何參數,但我主要需要前三個參數。另外,如果您在繪圖命令中正確設置了標籤,則應該這樣做。只需使用location參數調用圖例,並在每行中找到標籤。我有更好的運氣,使自己的傳奇如下。似乎工作在所有情況下,似乎沒有得到正確的其他方式。如果您不明白,請告訴我:

legendLabels = [] 
for i in range(modSize): 
    legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]  
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop 
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs) 
leg.get_title().set_fontsize(tick_size) 

您還可以使用leg來更改字體大小或幾乎圖例的任何參數。如上面的評論說

全球標題可以按照提供的鏈接添加文字來完成: http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html

f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center', 
     verticalalignment='top') 
3

suptitle似乎走的路,但是這是非常值得的figuretransFigure屬性,您可以使用:

fig=figure(1) 
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center') 
20

除了orbeckst answer一個也可能要轉移子情節下跌。下面是OOP風格的MWE:

import matplotlib.pyplot as plt 

fig = plt.figure() 
st = fig.suptitle("suptitle", fontsize="x-large") 

ax1 = fig.add_subplot(311) 
ax1.plot([1,2,3]) 
ax1.set_title("ax1") 

ax2 = fig.add_subplot(312) 
ax2.plot([1,2,3]) 
ax2.set_title("ax2") 

ax3 = fig.add_subplot(313) 
ax3.plot([1,2,3]) 
ax3.set_title("ax3") 

fig.tight_layout() 

# shift subplots down: 
st.set_y(0.95) 
fig.subplots_adjust(top=0.85) 

fig.savefig("test.png") 

給出:

enter image description here