Last active
April 3, 2020 16:44
-
-
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.
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_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