clemisch
clemisch

Reputation: 1034

Position text with background exactly in corner of matplotlib plot

I want to label my plots alphabetically in a multi-axes plot. With ax.text and manual coordinates, I can achieve that on a single figure:

ax.text(0.01, 0.96, 
    'A', transform=ax.transAxes, fontweight='bold', va='top', ha='left',
    backgroundcolor='k', color='white')

Working example

I want the black box to match the upper left corner exactly. Applying the above code on another figure does not work:

Not working example

Is there a way to match the black box of the text background with the axis corner exactly?

Upvotes: 1

Views: 1243

Answers (1)

clemisch
clemisch

Reputation: 1034

I found a consistent way that works regardless of the figure size or arangement of axes. For ax being an AxesSubplot object use:

ax.annotate(
    'A', 
    (0, 1),
    xytext=(4, -4),
    xycoords='axes fraction',
    textcoords='offset points',
    fontweight='bold',
    color='white',
    backgroundcolor='k',
    ha='left', va='top')

Note that my "global" matplotlib fontsize is set to 8. If you use another fontsize you probably have to change the xytext values.

Upvotes: 1

Related Questions