Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate plots in matplotlib figure

In a matplotlib figure I would like to enumerate all (sub)plots with a), b), c) and so on. Is there a way to do this automatically?

So far I use the individual plots' titles, but that is far from ideal as I want the number to be left aligned, while an optional real title should be centered on the figure.

like image 893
Se Norm Avatar asked Mar 19 '14 14:03

Se Norm


1 Answers

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.ascii_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)

example usage:

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

This seems useful enough to me that I put this in a gist : https://gist.github.com/tacaswell/9643166

like image 166
tacaswell Avatar answered Oct 02 '22 12:10

tacaswell