2014-03-19 7 views
5

In einer Matplotlib-Figur möchte ich alle (Sub-) Plots mit a), b), c) und so weiter aufzählen. Gibt es eine Möglichkeit, dies automatisch zu tun?Aufzählung in Matplotlib Abbildung

Bisher verwende ich die Titel der einzelnen Plots, aber das ist alles andere als ideal, da ich möchte, dass die Zahl linksbündig bleibt, während ein optionaler echter Titel auf die Figur zentriert sein sollte.

+0

Als eine Randnotiz hat eigentlich jede Achse drei Titel (links, rechts, Mitte), aber ich erinnere mich nicht, wenn das in 1.3 oder noch nur auf Master war. – tacaswell

Antwort

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) 

Beispiel Nutzung:

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() 

Dies scheint mir nützlich genug, dass ich diese in einem Kern: https://gist.github.com/tacaswell/9643166

1

ich eine Funktion schrieb dies automatisch zu tun, wo das Etikett eingeführt wird als Legende:

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() 

Die Position des Etiketts kann contro sein Mit loc Argument, der Abstand zur Achse kann mit borderpad Argument gesteuert werden (negativer Wert schiebt das Label außerhalb der Abbildung), und andere Optionen legend kann auch verwendet werden, wie fontsize. Das obige Skript gibt eine solche Figur: setlabel