Search code examples
pythonmatplotlibsubplotplot-annotations

Annotate Subplots in a Figure with A, B, C


When submitting papers to scientific journals one quite frequently needs to enumerate the different subplots of a figure with A, B, ... .

enter image description here

This sounds like a very common problem and I was trying to find an elegant way to do that automatically with matplotlib, but I was surprised to find nothing on it. But maybe I am not using the right search terms. Ideally, I am searching for a way to annotate such that the letters stay in place relative to the subplot if the figure is resized or the subplot is moved via fig.subplots_adjust, fig.tight_layout, or similar.

Any help or solution will appreciated.


Solution

  • If you want the annotation relative to the subplot then plotting it using ax.text seems the most convenient way to me.

    Consider something like:

    import numpy as np
    import matplotlib.pyplot as plt
    import string
    
    fig, axs = plt.subplots(2,2,figsize=(8,8))
    axs = axs.flat
    
    for n, ax in enumerate(axs):
        
        ax.imshow(np.random.randn(10,10), interpolation='none')    
        ax.text(-0.1, 1.1, string.ascii_uppercase[n], transform=ax.transAxes, 
                size=20, weight='bold')
    

    enter image description here

    edit:

    With the new plt.subplot_mosiac, the example above can be written as. Perhaps slightly more elagant. And consider adding constrained_layout=True.

    fig, axs = plt.subplot_mosaic("AB;CD", figsize=(10,10))
    
    for n, (key, ax) in enumerate(axs.items()):
    
        ax.imshow(np.random.randn(10,10), interpolation='none')    
        ax.text(-0.1, 1.1, key, transform=ax.transAxes, 
                size=20, weight='bold')