Search code examples
pythonmatplotlibsubplot

Matplotlib Mosaic Share Axes Labels and Ticks


Trying to share x and y axis across axes in figure using mosaic in Matplotlib.

Example from link:

mosaic = """
    AB
    CD
    """
fig = plt.figure(layout="constrained")
ax_dict = fig.subplot_mosaic(mosaic)

But this yields the x and y axis ticks and labels on all four axes objects.

I want the y axis ticks to be on the same scale with only labels on the A and C axes going down the left hand side of the figure.

Similarly I want the x-axis ticks and labels going across the bottom of the figure on the C and D axes, with axes objects above to be on the same scale and only have labels across the bottom.

Using other axes creation methods this format has worked:

# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)

But when trying this approach I get the following execption:

AttributeError: 'Rectangle' object has no property 'sharex'

What should I try next?


Solution

  • In general, you can share x and y axis by using the sharex and sharey methods that are defined on the axes object themselves.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplot_mosaic('YY\nAB\nCD', layout='constrained', figsize=(5, 3))
    
    ax['A'].plot(range(10), range(10))
    ax['C'].sharex(ax['A'])
    

    For sharing multiple axes, you can use a convenient one-liner:

    _ = [ax[i].sharey(ax['A']) for i in 'BCD']
    

    For turning on and off the axis labels, use:

    _ = [ax[i].tick_params(labelbottom=False) for i in "AB"]
    _ = [ax[i].tick_params(labelleft=False) for i in "BD"]
    

    This is what the above statements give:

    shared axes