Skip to content

letter_subplots : convenience function for adding panel labels #20182

Open

Description

@bagrow

Problem

Figures used in publications often consist of multiple panels. Matplotlib provides (amazing, ever-growing) functionality for creating and arranging multiple axes within a figure. When preparing a multi-panel figure for publication, you often need to label each panel so you can reference the individual subplots. It is common to use letters near the upper-left corner of each subplot.

(For an example five-panel figure and caption, see the last figure on https://www.internationalscienceediting.com/how-to-write-a-figure-caption/)

While Matplotlib provides much functionality for arranging axes, calling, e.g., plt.annotate to manually place every panel label is tedious. The Transformations Tutorial shows an example of manually labeling panels. I am not aware of an existing automatic solution.

While not all Matplotlib users are making figures for publication, many are. Given how common it is to label panels for publication figures, I believe it is worth making panel labeling more convenient.

Proposed Solution

I propose adding a convenience function letter_subplots to Matplotlib that takes a list of axes and adds letters automatically. Automatic lettering supports common journal formats (uppercase bold letters, lowercase letters in parentheses, etc.) or a list of arbitrary letters can be used.

Here is a gist of my letter_subplots: https://gist.github.com/bagrow/e3fd0bcfb7e107c0471d657b98ffc19d

A user can also change the position of labels, even setting a different position for each. Additional keyword arguments are passed to annotate.

I have used this function myself for several years and find it extremely helpful.

Here are some example uses (from the docstring):

Defaults:

>>> fig, axes = plt.subplots(1,3)
>>> letter_subplots() # boldfaced A, B, C

Common labeling schemes inferred from the first letter:

>>> fig, axes = plt.subplots(1,4)        
>>> letter_subplots(letters='(a)') # panels labeled (a), (b), (c), (d)

Fully custom lettering:

>>> fig, axes = plt.subplots(2,1)
>>> letter_subplots(axes, letters=['(a.1)', '(b.2)'], fontweight='normal')

Per-axis offsets:

>>> fig, axes = plt.subplots(1,2)
>>> letter_subplots(axes, xoffset=[-0.1, -0.15])

I understand that choosing the right defaults is critical. I like using uppercase bold letters, but the default should probably be whatever is most common across publications or otherwise determined through the same process as any of Matplotlib's style defaults.

Activity

  1. jklymak commented on May 7, 2021

    @jklymak
    Member

    Please also see #20147

  2. bagrow commented on May 7, 2021

    @bagrow
    Author

    I'm still on 3.2, but seems easy to add support for getting the labels out of that data structure. Thanks for the link.

  3. timhoffm commented on May 7, 2021

    @timhoffm
    Member

    For info: #15771 is a related PR that has stalled.

  4. timohillmann commented on May 8, 2021

    @timohillmann

    Regarding default positioning, I imagine one could follow the approach of the legend placing with some predefined positions.
    I wrote a similar function myself once, with default placing in the upper left corner outside the axis.
    This requires ascii_lowercase, which would enable easy switching between upper and lowercase.

    def add_label(ax, text='(a)', x0=None, y0=None, **kwargs):
        '''
        Adds labels to multi-axis figures.
        '''
    
        if isinstance(ax, np.ndarray):
            abc = [f'({letter})' for letter in list(ascii_lowercase)]
    
            f = ax.flat[0].get_figure()
            if y0 is None:
                y0 = f.subplotpars.top
            if x0 is None:
                x0 = f.subplotpars.left
            for i, _ax in enumerate(ax.flat):
                _ax.annotate(r'\textbf{{{}}} '.format(abc[i]),
                             xy=(-x0, y0), annotation_clip=False,
                             xycoords='axes fraction', weight='bold',
                             fontsize=plt.rcParams['font.size'],
                             va='bottom', **kwargs
                             )
        else:
            fig = ax.get_figure()
            if x0 is None:
                x0 = fig.subplotpars.left
            if y0 is None:
                y0 = fig.subplotpars.top
            if plt.rcParams['text.usetex'] is True:
                ax.annotate(r'\textbf {{{}}}'.format(text),
                            xy=(-x0, y0), annotation_clip=False,
                            xycoords='axes fraction', weight='bold',
                            fontsize=plt.rcParams['font.size'],
                            va='top', **kwargs,
                            )
            else:
                ax.annotate(r'{}'.format(text),
                            xy=(-x0, y0), annotation_clip=False,
                            xycoords='axes fraction', weight='bold',
                            fontsize=plt.rcParams['font.size'],
                            )
    
  5. tacaswell commented on May 8, 2021

    @tacaswell
    Member

    I have a couple of suggtions:

    Make the signature be

    def label_axes(fig, axes=None, ...):
        ...

    That way you do not need to have a pyplot dependency in the body of the function and it opens up the path to easily making it a (sub) Figure method in the future. While you could drop passing in axes all together then, but then you have no way to control the order or manually excluding some axes (like colorbar axes).

    We also need to have a bit of a think about how/if we want to recurse through sub-figures and if it is worth generalizing this to also label sub-figures.


    There is a get_label method on Axes, it would be good to make use of that, particuarly as subplot_mosaic sets that so if people do ax_dict = fig.subplot_mosaic('AA;BC') you get the right labels "for free" and now the order that we walk through the Axes does not matter! This will probably also require adding a flag like auto_index=None which has some behavior like if True -> ['a', 'b', ...], if False also go with ax.get_label() and if None act as if it is true iff all ax.get_label are empty otherwise act as False (this is a bit hard to explain, but makes sure we get the "obvious right behavior" for both fig.subplots(N, M) and fig.subplot_mosaic('AB;CD')

    Something like

    if auto_index is None:
        auto_index = all(ax.get_label() == '' for ax in ax_list)
    
    if auto_index:
        labels = [chr(97 + j) for j in range(len(ax_list))
    else:
        labels = [ax.get_label() for ax in ax_list]

    Rather than hard-coding mappings between strings and behavior, take in a function with a signature like

    def format_label(axes_label: str) -> str:
         ...

    If we follow the patten of "string or callable" like scipy does you can do something like

    def letter_subplots(..., format_func='a'):
    
        ...
        mapping = {
            "a": lambda x: x.lower(),
            "A": lambda x: x.upper(),
            "(a)": lambda x: "({x})".format(x=x.lower()),
            "(A)": lambda x: "({x})".format(x=x.upper()),
        }
        format_func = mapping.get(format_func, format_func)
        ...

    This way if someone needs formatting like [A] they can pass the function to make that happen! This also opens up a nice path for if people are using semantic names in subplot_mosaic like

    ax_dict = fig.subplot_mosaic([['hist', 'scatter'], ['hist', 'other_scatter']])

    Then they can pass something like

    letter_subplots(fig, format_func=lambda x: {'hist': 'B', 'scatter': 'A', 'other_scatter': 'C'}[x])

    This also opens a nice path for maintaining an (external?) collection of format functions tuned to particular journals!


    It may be useful to think about what function we would want to have to make it easy to write label_subplots_for_PRE, label_subplots_for_science, label_subplots_for_nature, label_subplots_for_your_domain_journal, etc .

  6. jklymak commented on May 8, 2021

    @jklymak
    Member

    I'm more worried about all the options wrt where you put the label, not what it contains or how it is formatted.

    You need to specify

    1. What the origin or anchor is and it coordinate system is
    2. What the offset is, and it's coordinate system
    3. Vertical and horizontal alignment of the text.
    4. Make sure that the choices align with object you expect it to align with in other subplots, including ones that may have a different size
    5. Making sure that these labels are not spilling into other axes. And are compatible with the layout engines.

    While some of the above sound easy, you will find they are hard to get right in general.

  7. github-actions commented on Oct 20, 2025

    @github-actions

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  8. tacaswell commented on Oct 20, 2025

    @tacaswell
    Member

    There appears to still be a number of design choices that need to be made (about both how to spell the formatting and how to specify where it goes).

    Do we want to keep this open or close due to lack of progress?

  9. timhoffm commented on Oct 20, 2025

    @timhoffm
    Member

    We should grow such functionality. Therefore, keep.

    There are different aspects, which may also be implemented incrementally:

    • Dedicated concept: from technical perspective, is this just a regular Text instance, or do we want to make it a dedicated conceptand is stored in a separate entity, like title. I'd go for separate entity.

    • should we reuse Axes.set_label or find a different name? I'm +/-0. label is a fitting term, but it is heavily overloaded in different context, e.g.

      • Name / API: Artist.set_label defines it as "a label that will be displayed in the legend"
      • for that reason we have made [Axis.set_label)[https://matplotlib.org/stable/api/_as_gen/matplotlib.axis.Axis.set_label.html#matplotlib.axis.Axis.set_label] raise. It's too easily confused with xlabel/ylabel; in particular the standard translation Axes.set_xlabel -> Axes.xaxis.set_label was never valid.
      • Also an argument against Axes.set_label: We likely need different signatures, such as set_label('a)', position="top-left", fontsize=16)

      See also [MNT]: Remove the label API from Artist #29422.

    • Positioning: How much flexibility do we need for positioning?

      • If it's inside the Axes, typically the four corners should be sufficient. Do we want auto-positioning like legend? - I think not, because it would be awkward to have the labels in different positions depending on data content for a grid of subplots. Also, the label is typically short, so collision with data is less of an issue.
      • It could also be in the title line at the very left.
      • It could also be outside the whole Axes with decoration (typically in the top-left corner) - this would need additional handling in the layout manager.

      We can start small and only have fixed positions inside the Axes.

    • Figure / grid-level API: Functions that automatically label a set of Axes, e.g. a), b), c), ... or from subplot_mosaic names.

    Overall, I'd start small with defining the "Axes label" (name t.b.d.) and make it possible to set it on individual Axes. We can later expand on positioning and high-level functions.

  10. added
    keepItems to be ignored by the “Stale” Github Action
    and removed
    status: inactiveMarked by the “Stale” Github Action
    on Oct 20, 2025
  11. jklymak commented on Oct 20, 2025

    @jklymak
    Member

    We already have three titles. Do we want a fourth? I always just do this as ax.set_title("a)", loc='left')

  12. rcomer commented on Oct 20, 2025

    @rcomer
    Member

    Does this need to do anything that AnchoredText can’t do?
    https://matplotlib.org/stable/gallery/axes_grid1/simple_anchored_artists.html

  13. timhoffm commented on Oct 21, 2025

    @timhoffm
    Member

    We already have three titles. Do we want a fourth?

    No. These are already two titles to many. The point is that a "panel label" would be a different logical concept, which would manifest in different features, e.g. positioning capabilities and auto-labelling.

    Does this need to do anything that AnchoredText can’t do?

    Likely, AnchoredText is sufficient, and it could be the way we implement this. But we would want a more straight forward user-facing API such as ax.set_panel_label(...) / fig.label_panels() (names t.b.d.) and not at = AnchoredText(...); ax.add_artist(at).

  14. timohillmann commented on Oct 22, 2025

    @timohillmann

    I guess we should also think about what the options are that we want to present to a user, that make the api easy and intuitive to use, e.g., for label placement.
    For my personal use, I usually encounter that either (a) place labels inside the panel or (b) outside the panel, i.e,. next to axes tick labels. Another options is the location, with upper left probably being what most people would use. Similar to the legend functionality, maybe we need some form of borderpad.

    Years ago, I had posted a version of my own code for that purpose. It's not as good as I would like it, but it works and haven't really changed it since (I should though). @jklymak mentioned after I posted that some concerns about label placing/anchor placing. Not sure if that was directed towards my (incomplete) solution. I found (for my purposes) that (-fig.subplotpars.left fig.subplotpars.top) was usually a good starting point for placing labels on the top-left outside of the panel.

  15. jklymak commented on Oct 22, 2025

    @jklymak
    Member

    In general, we do layout using constrained layout these days, were figsubplotpars.left etc are ignored.

    Constrained layout should not have a problem laying out an added anchored text so long as it's distance from the axes doesn't keep changing. eg it would be much better if the distance of the label from the axes edge (lets say upper left corner) didn't change if the axes changed size.

    If I were to do this, I'd place the label a fixed physical distance from the upper left corner of the (and perhaps allow other anchors or named anchors). This is what has been done in the second example at https://matplotlib.org/stable/gallery/text_labels_and_annotations/label_subplots.html

    You could also do via AnchoredOffsetBox (as in this example: https://matplotlib.org/stable/gallery/misc/anchored_artists.html). I'd be pretty wary about using axes_grid1 methods like AnchoredText.

    @timohillmann Your method of using annotate also seems fine, but I'd not use xycoords='axes fraction', but rather xycoords='figure points' since the label shouldn't get further from the axes if the axes gets bigger.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    New featurekeepItems to be ignored by the “Stale” Github Action

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions