Matplotlib tight_layout() doesn't take into account figure suptitle

后端 未结 10 1566
既然无缘
既然无缘 2020-11-28 18:02

If I add a subtitle to my matplotlib figure it gets overlaid by the subplot\'s titles. Does anybody know how to easily take care of that? I tried the tight_layout()

相关标签:
10条回答
  • 2020-11-28 18:32

    You could manually adjust the spacing using plt.subplots_adjust(top=0.85):

    import numpy as np
    import matplotlib.pyplot as plt
    
    f = np.random.random(100)
    g = np.random.random(100)
    fig = plt.figure()
    fig.suptitle('Long Suptitle', fontsize=24)
    plt.subplot(121)
    plt.plot(f)
    plt.title('Very Long Title 1', fontsize=20)
    plt.subplot(122)
    plt.plot(g)
    plt.title('Very Long Title 2', fontsize=20)
    plt.subplots_adjust(top=0.85)
    plt.show()
    
    0 讨论(0)
  • 2020-11-28 18:34

    I have struggled with the matplotlib trimming methods, so I've now just made a function to do this via a bash call to ImageMagick's mogrify command, which works well and gets all extra white space off the figure's edge. This requires that you are using UNIX/Linux, are using the bash shell, and have ImageMagick installed.

    Just throw a call to this after your savefig() call.

    def autocrop_img(filename):
        '''Call ImageMagick mogrify from bash to autocrop image'''
        import subprocess
        import os
    
        cwd, img_name = os.path.split(filename)
    
        bashcmd = 'mogrify -trim %s' % img_name
        process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)
    
    0 讨论(0)
  • 2020-11-28 18:37

    I had a similar issue that cropped up when using tight_layout for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle at a certain distance above your top subplot:

    import matplotlib.pyplot as plt
    
    n_rows = 50
    n_col = 4
    fig, axs = plt.subplots(n_rows, n_cols)
    
    #make plots ...
    
    # define y position of suptitle to be ~20% of a row above the top row
    y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
    fig.suptitle('My Sup Title', y=y_title_pos)
    

    For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.

    0 讨论(0)
  • This website has a simple solution to this with an example that worked for me. The line of code that does the actual leaving of space for the title is the following:

    plt.tight_layout(rect=[0, 0, 1, 0.95]) 
    

    Here is an image of proof that it worked for me:

    0 讨论(0)
提交回复
热议问题