Search code examples
pythonmatplotlibgraphvisualization

Create symmetric figures when using matplotlib labels


I am using plt.subplots with both ax.set_ylabel and fig.supylabel. However, this creates figures that are off-centered.

Is it possible to automatically increase the right margin such that the red line is at the center of the figure? enter image description here In the case I am doing this manually, how can I precisely measure by how much I should increase the right margin?


Solution

  • How about this:

    fig = plt.figure()
    ax1 = fig.add_subplot(1,2,1)
    ax2 = fig.add_subplot(1,2,2)
    x = np.arange(50)
    ax1.plot(x,np.sin(x))
    ax2.plot(x,np.sin(x))
    ax1.set_ylim(-1,1)
    ax2.set_ylim(-1,1)
    ax2.set_yticklabels('')
    ax1.set_title('damped')
    ax2.set_title('undamped')
    ax1.set_ylabel('amplitude')
    fig.suptitle('Different types of oscillations')
    

    Output:

    enter image description here

    ---edit---

    Try this:

    import matplotlib.gridspec as grd
    
    fig = plt.subplots()
    
    gs = grd.GridSpec(1, 2, wspace=0.5)
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    
    x = np.arange(50)
    ax1.plot(x,np.sin(x))
    ax2.plot(x,np.sin(x))
    
    ax1.set_title('damped')
    ax2.set_title('undamped')
    ax1.set_ylabel('amplitude')
    

    The keypoint is gs = grd.GridSpec(1, 2, wspace=0.5). Adjust wspace as you like. The plot below is for wspace=0.5

    enter image description here