Getting the same subplot size using matplotlib imshow and scatter

It’s not perfectly clear what your desired outcome is.

  1. You may use automatic aspect on the image

    ax.imshow(z, aspect="auto")
    

    enter image description here

  2. Or you may set the aspect of the line plot depending on its axis limits such that it gets the same size as the image (in case the image has equal x and y sizes)

    asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
    ax2.set_aspect(asp)
    

    enter image description here
    Complete code:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0,10,20)
    y = np.sin(x)
    z = np.random.rand(100,100)
    
    fig, (ax, ax2) = plt.subplots(ncols=2)
    
    ax.imshow(z)
    ax2.plot(x,y, marker=".")
    
    asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
    ax2.set_aspect(asp)
    
    plt.show()
    

    If the image does not have equal limits (is not square), one still needs to divide by the aspect of the image:

    asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
    asp /= np.abs(np.diff(ax1.get_xlim())[0] / np.diff(ax1.get_ylim())[0])
    ax2.set_aspect(asp)
    
  3. More sophisticated solutions:

    • This answer for using the subplot parameters to achieve a certain aspect.

    • If you want to use mpl_toolkits and make your hands dirty, this answer would be a good read.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)