Skip to content

Instantly share code, notes, and snippets.

@Kappie
Last active April 3, 2020 16:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kappie/02a807b98c6a448fbe8e35072b3969fc to your computer and use it in GitHub Desktop.
Save Kappie/02a807b98c6a448fbe8e35072b3969fc to your computer and use it in GitHub Desktop.
Automatically add figure labels (a), (b), (c), etc. to axes. Labels are located at the top-left of the axis, at the same horizontal position as the y-label.
def add_labels(axes, style=r'(%s)'):
"""
Adds figure labels (a), (b), (c), etc. to axes.
Must be called after plt.tight_layout().
"""
alphabet = 'abcdefghijkl'
labels = [style % letter for letter in alphabet]
# EXTREME hack alert.
# For some magical reason, this is necessary to get the bounding boxes correct.
axes[0].figure.savefig("/tmp/hallo.pdf")
for i, ax in enumerate(axes):
transform = ax.transAxes
inv_transform = ax.transAxes.inverted()
ylabelbox = ax.yaxis.label.get_window_extent()
axbox = ax.get_window_extent()
labelx_pixel = ylabelbox.x0
labely_pixel = axbox.y1
labelx, labely = inv_transform.transform((labelx_pixel, labely_pixel))
ax.text(labelx, labely, labels[i], transform=transform, va='top', ha='left')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment