Skip to content

Instantly share code, notes, and snippets.

@tacaswell
Last active August 13, 2021 04:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tacaswell/9643166 to your computer and use it in GitHub Desktop.
Save tacaswell/9643166 to your computer and use it in GitHub Desktop.
A quick little function to walk through the axes in a Figure instance and label each one with annotate.
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)
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()
@MerlinPendragon
Copy link

Hi, I saw your answer on StackOverflow. Thank you for helping me out! But there is a slight problem with python 3. The problem is that string.lowercase is now deprecated in python3, so perhaps you should change

labels = string.lowercase

to

labels = string.ascii_lowercase

<3

@pgriewank
Copy link

Also came here through stack overflow, also had to change labels to string.ascii_lowercase, also very thankful for you posting your fix!

Cheers,

@shomikverma
Copy link

This labels colorbars as well, to fix, filter out colorbars from axes:

axes = [ax for ax in fig.axes if ax.get_label() != '<colorbar>']
for ax, lab in zip(axes, labels):
    ...etc...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment