Skip to content

[Feature request] span axis labels #464  #11

Closed

Description

@cvanelteren

I want to revive the issue raised here:

proplot-dev/proplot#464

The feature request describes a more flexible approach to sharing axis labels. I haven't found a clean way to use the mpl /uplt syntax to easily share labels in a "complex" plot, i.e. a plot in which not all axis are shared but some.

I would propose that we can have something like

import ultraplot as plt
layout = [
[1, 2, 3],
[4, 5, 3]
]
fig, ax = plt.subplots(layout, share = 0, figsize = (4,4))
ax[0:2].format(xlabel = "shared group 1")

Yielding:
image

In this way we could capitalize on the existing format function but extend its functionality to share formatting only on certain properties and not all.

However what I wish to achieve is this:

image

which can be achieved by

layout = [
    [1, 2, 3],
    [4, 5, 3]
]
fig, ax = plt.subplots(layout, share = 0, figsize = (4,4))

shared = fig.add_subplot(2, 3, (1, 2))
shared.set_xticks([])
shared.set_yticks([])
shared.set_frame_on(False)
shared.grid(False)
shared.set_xlabel("Testing this out", labelpad = 20)

Happy to hear your thoughts in this!

Activity

  1. pratiman-91 commented on Jan 12, 2025

    @pratiman-91
    Contributor

    I think it would be a nice feature to add.

  2. cvanelteren commented on Jan 13, 2025

    @cvanelteren
    CollaboratorAuthor

    So apparantly the codebase already have something in place to do this. For example I could write

    import ultraplot as plt
    
    fig, ax = plt.subplots(ncols = 3, nrows = 3, sharex = 0, sharey = 0, share = 0, figsize = (3, 3))
    
    axes = [ax[0,0], ax[1, 0]]
    ax.format(xlabel = "B")
    fig.format(share_xlabels = axes)
    
    
    ax[0].set_xlabel("A")
    axes = [ax[0,1], ax[1, 1]]
    fig.format(share_xlabels = axes)
    
    ax[0, 1].set_xlabel("C")
    plt.show(block = 1)

    image
    Neat!

    However, it gets a bit funky with more complicated demands:

    image

    Produced by

    import ultraplot as plt
    fig, ax = plt.subplots(ncols = 3, nrows = 3, sharex = 0, sharey = 0, share = 0, figsize = (3, 3))
    axes = [ax[0,0], ax[1, 0], ax[0, 1], ax[1,1]]
    ax.format(xlabel = "A")
    fig.format(share_xlabels = axes)
    ax[0].set_xlabel("B")
    plt.show(block = 1)
  3. cvanelteren commented on Jan 13, 2025

    @cvanelteren
    CollaboratorAuthor

    I will do some more digging as the codebase has the right functions to get this working

  4. Mickychen00 commented on Jan 14, 2025

    @Mickychen00

    Hi. I found when I set sharey = 3 or sharey = True. It seems that just yticklabels were removed but not real sharey.
    Case sharey = 3
    image

    Case sharey = 0
    image

    Currently, I need to set specific ylim to let them be real "shared"
    I don't know if it's related to this feature.

  5. cvanelteren commented on Jan 14, 2025

    @cvanelteren
    CollaboratorAuthor

    It's related but not the same. The docs state

    
    
        False or 0: Axis sharing is disabled.
    
        'labels', 'labs', or 1: Axis labels are shared, but nothing else. Labels will appear on the leftmost and bottommost subplots.
    
        'limits', 'lims', or 2: Same as 1, but axis limits, axis scales, and major and minor tick locations and formatting are also shared.
    
        True or 3 (default): Same as 2, but axis tick labels are also shared. Tick labels will appear on the leftmost and bottommost subplots.
    
        'all' or 4: Same as 3, but axis limits, axis scales, and axis ticks are shared even between subplots not in the same row or column.
    

    I want this feature to be available on a subset of axes not all or nothing.

  6. Mickychen00 commented on Jan 14, 2025

    @Mickychen00

    Great idea. More granular subgraph labeling.
    By the way, I just tested the same code in Proplot (off course using old matplotlib == 3.4.3 and numpy == 1.23.0)
    It shows rightly comprared to the newest version of Ultraplot.
    image

    Apparently, I can explicitly set them by "ylim" by way of compromise.
    Is it related to matplotlib's code changes?

  7. cvanelteren commented on Jan 14, 2025

    @cvanelteren
    CollaboratorAuthor

    What do you mean that it looks righly? Ultraplot support newer versions of mpl than 3.4.3 and is not backwards compatible with <3.9

  8. Mickychen00 commented on Jan 14, 2025

    @Mickychen00

    I mean when I set fig_sd = pplt.figure(sharey='all') or fig_sd = pplt.figure(sharey=True). Proplot will let each subplot's ylim be the same; however, Ultraplot will only remove the y-tick labels from subplots that are not on the leftmost side, even though their y-limits differ.

  9. cvanelteren commented on Jan 14, 2025

    @cvanelteren
    CollaboratorAuthor
  10. cvanelteren commented on Jan 14, 2025

    @cvanelteren
    CollaboratorAuthor

    Think I found the issue! https://matplotlib.org/stable/api/prev_api_changes/api_changes_3.6.0.html#groupers-from-get-shared-x-axes-get-shared-y-axes-will-be-immutable

    made some local changes and now it is sharing properly. Will make a PR for this for review

  11. Mickychen00 commented on Jan 14, 2025

    @Mickychen00

    Great to hear it! Thanks for the prompt fix.

  12. cvanelteren commented on Feb 16, 2025

    @cvanelteren
    CollaboratorAuthor

    Small update, getting some interesting results:

    Image

    code
    import ultraplot as plt, numpy as np
    import matplotlib.transforms as mtransforms
    
    
    def hide(ax):
        for which in "xy":
            getattr(ax, f"set_{which}ticklabels")([])
        ax.tick_params(size=0, width=0, which="both", axis="both")
        for spine in ax.spines.values():
            spine.set_visible(False)
        ax.set_facecolor("none")
        ax.patch.set_visible(False)
    
    
    def share_labels(
        fig,
        axes,
        xlabel=None,
        ylabel=None,
        xpad=15.0,
        ypad=15.0,
    ):
        """Create shared labels using GridSpec for proper alignment."""
        bbox = mtransforms.Bbox.union([ax.get_position() for ax in axes])
    
        if xlabel is None and ylabel is None:
            return bbox
    
        # Get reference axis for GridSpec
        ref_ax = axes[0]
        gs = ref_ax.get_gridspec()
    
        # Get the subplot spec for our shared axes region
        # Find the min/max row/col indices that cover our axes
        rows = set()
        cols = set()
        for ax in axes:
            ss = ax.get_subplotspec()
            rows.update(range(ss.rowspan.start, ss.rowspan.stop))
            cols.update(range(ss.colspan.start, ss.colspan.stop))
    
        row_start, row_stop = min(rows), max(rows) + 1
        col_start, col_stop = min(cols), max(cols) + 1
    
        # Create subplot spec for the dummy axis
        ss = gs[row_start:row_stop, col_start:col_stop]
    
        # Add the dummy subplot
        dummy = fig.add_subplot(ss)
        hide(dummy)
    
        if xlabel:
            dummy.set_xlabel(xlabel, labelpad=xpad)
        if ylabel:
            dummy.set_ylabel(ylabel, labelpad=ypad)
    
        return bbox, dummy
    
    
    fig, ax = plt.subplots(
        ncols=3,
        nrows=3,
        share=0,
        journal="nat1",
    )
    
    axes1 = [ax[0, 0], ax[1, 0]]
    share_labels(fig, axes1, "A", "AA")
    x, y = np.random.rand(2, 100)
    ax.plot(x, y)
    
    axes2 = [ax[0, 1], ax[1, 1]]
    share_labels(fig, axes2, "C", "CC")
    
    axes3 = [ax[0, 2], ax[1, 2], ax[2, 2]]
    share_labels(fig, axes3, "B")
    
    
    plt.show(block=1)
  13. added
    enhancement
    on Apr 13, 2025
  14. pratiman-91 commented on Apr 20, 2025

    @pratiman-91
    Contributor

    @cvanelteren I have been thinking about this, and one of the elegant ways to make sub-figures rather than using axes. Here is an idea: if we can convert a group of axes to a subfigure, then sharing labels would be made easy.

    I think this can be done using sub-figures. For example,

    import matplotlib.pyplot as plt
    fig = plt.figure(layout='constrained', figsize=(10, 8))
    
    subfigs = fig.subfigures(1, 2, wspace=0.07)
    
    subfigs[0].suptitle('subfigs[0]')
    subfigs[1].suptitle('subfigs[1]')
    
    subfigsnest = subfigs[0].subfigures(2, 1, height_ratios=[1, 1.4])
    
    subfigsnest[0].supxlabel("Shared X-Label")
    
    axsnest0 = subfigsnest[0].subplots(1, 2, sharey=True)
    axsnest1 = subfigsnest[1].subplots(1, 2, sharex=True)
    
    axsRight = subfigs[1].subplots(1, 1)
    
    plt.show()

    will yield

    Image

  15. cvanelteren commented on Apr 21, 2025

    @cvanelteren
    CollaboratorAuthor

    Hmm maybe you are right. I have little experience with subfigures. At the time they were a bit limited. Will have a look soon.

  16. pratiman-91 commented on Aug 2, 2025

    @pratiman-91
    Contributor

    @cvanelteren Maybe this could help to close this ticket and can be added in the documentation.

    import ultraplot as uplt
    fig = uplt.figure(layout='constrained', figsize=(10, 8))
    
    subfigs = fig.subfigures(nrows=1, ncols=2, wspace=0.07)
    
    subfigs[0].suptitle('subfigs 1')
    subfigs[1].suptitle('subfigs 2')
    
    subfigsnest = subfigs[0].subfigures(nrows=2, ncols=1)
    
    subfigsnest[0].supxlabel("Sub-sub Figure Shared X-Label (1)")
    
    subfigs[0].supylabel("Sub-Figure Shared Y-Label")
    fig.supxlabel("Main Figure Shared X-Label")
    
    axsnest0 = subfigsnest[0].subplots(nrows=1, ncols=2, sharey=True)
    axsnest1 = subfigsnest[1].subplots(nrows=1, ncols=2, sharex=True)
    
    axsRight = subfigs[1].subplots(nrows=1, ncols=1)
    
    uplt.show()
    Image
  17. cvanelteren commented on Aug 3, 2025

    @cvanelteren
    CollaboratorAuthor

    I am aware of subfigures and I think this is indeed a nice way to approach it; however I still think that's a lot of boiler plate for just spanning some labels. Will keep this in mind tho was I am not currently working on this problem.

  18. cvanelteren commented on Jan 11, 2026

    @cvanelteren
    CollaboratorAuthor

    Implemented on main.

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions