Creating square subplots (of equal height and width) in matplotlib

前端 未结 2 2004
攒了一身酷
攒了一身酷 2020-12-30 22:17

When I run this code

from pylab import *

figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2,          


        
2条回答
  •  暖寄归人
    2020-12-30 22:44

    Your problem in setting the aspect of the plots is coming in when you're using sharex and sharey.

    One workaround is to just not used shared axes. For example, you could do this:

    from pylab import *
    
    figure()
    subplot(121, aspect='equal')
    plot([1, 2, 3], [1, 2, 3])
    subplot(122, aspect='equal')
    plot([1, 2, 3], [1, 2, 3])
    show()
    

    However, a better workaround is to change the "adjustable" keywarg... You want adjustable='box', but when you're using shared axes, it has to be adjustable='datalim' (and setting it back to 'box' gives an error).

    However, there's a third option for adjustable to handle exactly this case: adjustable="box-forced".

    For example:

    from pylab import *
    
    figure()
    ax1 = subplot(121, aspect='equal', adjustable='box-forced')
    plot([1, 2, 3], [1, 2, 3])
    subplot(122, aspect='equal', adjustable='box-forced', sharex=ax1, sharey=ax1)
    plot([1, 2, 3], [1, 2, 3])
    show()
    

    Or in more modern style (note: this part of the answer wouldn't have worked in 2010):

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(ncols=2, sharex=True, sharey=True)
    for ax in axes:
        ax.plot([1, 2, 3], [1, 2, 3])
        ax.set(adjustable='box-forced', aspect='equal')
    
    plt.show()
    

    Either way, you'll get something similar to:

提交回复
热议问题