Created
March 15, 2021 16:18
-
-
Save blaylockbk/8ce5d7d12349ef27a2ad35341e2fcc4b to your computer and use it in GitHub Desktop.
Add figure letters to matplotlib axes
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
def add_fig_letters(axes, offset=.07, facecolor='#f9ecd2', **kwargs): | |
""" | |
Add a figure letter to top-left corner for all axes | |
Like is done in a publication figure, all axes are labeled with a | |
letter so individual axes can be referred to from the text. | |
Paramters | |
--------- | |
axes : list | |
A list of matplotlib axes | |
offset : number or tuple | |
Fine tune the placement of the axes. | |
If a single number given, will move in both x and y direction. | |
If a tuple is give, first number is adjustment in x, | |
second number is adjustmen in y | |
Example | |
------- | |
fig, axes = plt.subplots(4,4) | |
add_fig_letters(axes) | |
""" | |
if not hasattr(offset, '__len__'): | |
offset = (offset, offset) | |
assert len(offset) == 2, 'Offset must be a number or tuple' | |
if not hasattr(axes, 'flat'): | |
np.array(axes) | |
### Add letters to plots | |
import string | |
try: | |
axes = axes.flat | |
except: | |
pass | |
for i, (ax, letter) in enumerate(zip(axes, string.ascii_lowercase)): | |
plt.sca(ax) | |
# Add figure letter | |
box_prop = dict(boxstyle='round', | |
facecolor=facecolor, | |
alpha=1, | |
linewidth=.5) | |
plt.text(0+offset[0], 1-offset[1], f'{letter}', | |
transform=ax.transAxes, fontfamily='monospace', | |
va='top', ha='left', | |
bbox=box_prop, zorder=100_000, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This little function adds a quick letter label to each axes in a multi-axis matplotlib figure. I always need to do this when I create figures for publications, and this function makes the styles consistent for all my figures.
The function can be found in my toolbox.