Last active
August 13, 2021 04:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Also came here through stack overflow, also had to change labels to string.ascii_lowercase, also very thankful for you posting your fix!
Cheers,
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
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