Search code examples
pythonmatplotlib

How to align the axes of a figure in matplotlib?


I have a figure with a 2x2 grid of plt.Axes (one of which is actually removed). Axes of the same row (resp. col) share the same y-axis (resp. x-axis) range. For example,

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(2, 2)
axs[0, 0].imshow(np.zeros((2, 2)))
axs[0, 1].imshow(np.zeros((2, 1)))
axs[1, 0].imshow(np.zeros((1, 2)))
axs[1, 1].remove()
plt.show(block=True)

This looks like this:

enter image description here

I want the axes to be aligned, that is, that points with the same x (resp. y) coordinates in the axes of the same column (resp. row) also share the same x (resp. y) coordinate in the figure. What do I need to change to achieve this?

I tried sharex='col', sharey='row' as it seemed to provide a solution in other answers, but all I got is this change in ticks, not in figure alignment:

enter image description here


Solution

  • You could try to allocate twice as much space for upper plots with matplotlib.pyplot.subplot_mosaic like this:

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    fig, ax = plt.subplot_mosaic(
        [
            ['00', '01'],
            ['00', '01'],
            ['10', '11']
        ],
        layout='constrained'
    )
    
    ax['00'].imshow(np.zeros((2, 2)))
    ax['01'].imshow(np.zeros((2, 1)))
    ax['10'].imshow(np.zeros((1, 2)))
    ax['11'].remove()
    
    plt.show()
    

    VoilĂ :

    enter image description here