Changing matplotlib subplot size/position after axes creation

前端 未结 3 1404
难免孤独
难免孤独 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()
    
    0 讨论(0)
  • 2021-02-04 01:58

    You can create a figure with one subplot that spans two rows and one subplot that spans one row using the rowspan argument to subplot2grid:

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax1 = plt.subplot2grid((3,1), (0,0), rowspan=2)
    ax2 = plt.subplot2grid((3,1), (2,0))
    plt.show()
    

    enter image description here

    If you want to change the subplot size and position after it's been created you can use the set_position method.

    ax1.set_position([0.1,0.1, 0.5, 0.5])
    

    Bu you don't need this to create the figure you described.

    0 讨论(0)
  • 2021-02-04 02:00

    Thanks to Molly pointing me in the right direction, I have a solution:

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    
    fig = plt.figure()
    
    ax = fig.add_subplot(111)
    
    gs = gridspec.GridSpec(3,1)
    ax.set_position(gs[0:2].get_position(fig))
    ax.set_subplotspec(gs[0:2])              # only necessary if using tight_layout()
    
    fig.add_subplot(gs[2])
    
    fig.tight_layout()                       # not strictly part of the question
    
    plt.show()
    
    0 讨论(0)
提交回复
热议问题