Repository navigation
Description
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, CCommon 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
jklymak commentedon May 7, 2021
Please also see #20147
bagrow commentedon May 7, 2021
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.
timhoffm commentedon May 7, 2021
For info: #15771 is a related PR that has stalled.
timohillmann commentedon May 8, 2021
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.tacaswell commentedon May 8, 2021
I have a couple of suggtions:
Make the signature be
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
axesall 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_labelmethod on Axes, it would be good to make use of that, particuarly assubplot_mosaicsets that so if people doax_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 likeauto_index=Nonewhich has some behavior like if True -> ['a', 'b', ...], if False also go withax.get_label()and if None act as if it is true iff allax.get_labelare empty otherwise act as False (this is a bit hard to explain, but makes sure we get the "obvious right behavior" for bothfig.subplots(N, M)andfig.subplot_mosaic('AB;CD')Something like
Rather than hard-coding mappings between strings and behavior, take in a function with a signature like
If we follow the patten of "string or callable" like scipy does you can do something like
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 insubplot_mosaiclikeThen they can pass something like
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 .jklymak commentedon May 8, 2021
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
While some of the above sound easy, you will find they are hard to get right in general.
github-actions commentedon Oct 20, 2025
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!
tacaswell commentedon Oct 20, 2025
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?
timhoffm commentedon Oct 20, 2025
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_labelor find a different name? I'm +/-0.labelis a fitting term, but it is heavily overloaded in different context, e.g.xlabel/ylabel; in particular the standard translationAxes.set_xlabel->Axes.xaxis.set_labelwas never valid.Axes.set_label: We likely need different signatures, such asset_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?
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.
jklymak commentedon Oct 20, 2025
We already have three titles. Do we want a fourth? I always just do this as ax.set_title("a)", loc='left')
rcomer commentedon Oct 20, 2025
Does this need to do anything that
AnchoredTextcan’t do?https://matplotlib.org/stable/gallery/axes_grid1/simple_anchored_artists.html
jklymak commentedon Oct 20, 2025
Or https://matplotlib.org/stable/gallery/misc/anchored_artists.html, or https://matplotlib.org/stable/gallery/text_labels_and_annotations/label_subplots.html
timhoffm commentedon Oct 21, 2025
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.
Likely,
AnchoredTextis sufficient, and it could be the way we implement this. But we would want a more straight forward user-facing API such asax.set_panel_label(...)/fig.label_panels()(names t.b.d.) and notat = AnchoredText(...); ax.add_artist(at).timohillmann commentedon Oct 22, 2025
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 leftprobably being what most people would use. Similar to the legend functionality, maybe we need some form ofborderpad.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.
jklymak commentedon Oct 22, 2025
In general, we do layout using constrained layout these days, were
figsubplotpars.leftetc 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 ratherxycoords='figure points'since the label shouldn't get further from the axes if the axes gets bigger.