Changing matplotlib subplot size/position after axes creation

前端 未结 3 1420
难免孤独
难免孤独 2021-02-04 01:05

Is it possible to set the size/position of a matplotlib subplot after the axes are created? I know that I can do:

import matplotlib.pyplot as plt

ax = plt.subp         


        
3条回答
  •  面向向阳花
    2021-02-04 01:55

    You can avoid ax.set_position() by using fig.tight_layout() instead which recalculates the new gridspec:

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    
    # create the first axes without knowing of further subplot creation
    fig, ax = plt.subplots()
    ax.plot(range(5), 'o-')
    
    # now update the existing gridspec ...
    gs = gridspec.GridSpec(3, 1)
    ax.set_subplotspec(gs[0:2])
    # ... and recalculate the positions
    fig.tight_layout()
    
    # add a new subplot
    fig.add_subplot(gs[2])
    fig.tight_layout()
    plt.show()
    

提交回复
热议问题