2014-03-19 34 views
5

在matplotlib圖中,我想枚舉所有(子)圖a),b),c)等等。有沒有辦法自動做到這一點?枚舉matplotlib中的圖塊

到目前爲止,我使用的是單個地塊的標題,但這並不理想,因爲我希望數字左對齊,而可選的真實標題應該以圖形爲中心。

+0

作爲一個方面說明,每個軸實際上有三個標題(左,右,中),但我不記得它是在1.3還是隻在主。 – tacaswell

回答

6
import string 
from itertools import cycle 
from six.moves import zip 

def label_axes(fig, labels=None, loc=None, **kwargs): 
    """ 
    Walks through axes and labels each. 

    kwargs are collected and passed to `annotate` 

    Parameters 
    ---------- 
    fig : Figure 
     Figure object to work on 

    labels : iterable or None 
     iterable of strings to use to label the axes. 
     If None, lower case letters are used. 

    loc : len=2 tuple of floats 
     Where to put the label in axes-fraction units 
    """ 
    if labels is None: 
     labels = string.lowercase 

    # re-use labels rather than stop labeling 
    labels = cycle(labels) 
    if loc is None: 
     loc = (.9, .9) 
    for ax, lab in zip(fig.axes, labels): 
     ax.annotate(lab, xy=loc, 
        xycoords='axes fraction', 
        **kwargs) 

用法示例:

from matplotlib import pyplot as plt 
fig, ax_lst = plt.subplots(3, 3) 
label_axes(fig, ha='right') 
plt.draw() 

fig, ax_lst = plt.subplots(3, 3) 
label_axes(fig, ha='left') 
plt.draw() 

這似乎有用足夠,我認爲我把這個在一個要點:https://gist.github.com/tacaswell/9643166

1

我寫了一個函數來自動執行此操作,在引入標籤作爲一個傳說:

import numpy 
import matplotlib.pyplot as plt 

def setlabel(ax, label, loc=2, borderpad=0.6, **kwargs): 
    legend = ax.get_legend() 
    if legend: 
     ax.add_artist(legend) 
    line, = ax.plot(numpy.NaN,numpy.NaN,color='none',label=label) 
    label_legend = ax.legend(handles=[line],loc=loc,handlelength=0,handleheight=0,handletextpad=0,borderaxespad=0,borderpad=borderpad,frameon=False,**kwargs) 
    label_legend.remove() 
    ax.add_artist(label_legend) 
    line.remove() 

fig,ax = plt.subplots() 
ax.plot([1,2],[1,2]) 
setlabel(ax, '(a)') 
plt.show() 

該標籤的位置可以控制用loc參數進行填充,可以用borderpad參數(負值將標籤推到圖的外部)來控制與軸的距離,還可以使用其他可用於legend的選項,例如fontsize。上面的腳本給出了這樣的數字: setlabel