首页 文章

使用matplotlib中的许多子图改进子图大小/间距

提问于
浏览
200

this question非常相似,但不同之处在于我的身材可以达到需要的大小 .

我需要在matplotlib中生成一堆垂直堆叠的图 . 结果将使用figsave保存并在网页上查看,因此我不关心最终图像的高度,只要子图间隔开,这样它们就不会重叠 .

无论我有多大的数字,子图总是似乎重叠 .

我的代码目前看起来像

import matplotlib.pyplot as plt
import my_other_module

titles, x_lists, y_lists = my_other_module.get_data()

fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
    plt.subplot(len(titles), 1, i)
    plt.xlabel("Some X label")
    plt.ylabel("Some Y label")
    plt.title(titles[i])
    plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)

6 回答

  • 41

    你可以试试subplot_tool()

    plt.subplot_tool()
    
  • 202

    您可以使用 plt.subplots_adjust 更改子图之间的间距(source)

    通话签名:

    subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
    

    参数含义(和建议的默认值)是:

    left  = 0.125  # the left side of the subplots of the figure
    right = 0.9    # the right side of the subplots of the figure
    bottom = 0.1   # the bottom of the subplots of the figure
    top = 0.9      # the top of the subplots of the figure
    wspace = 0.2   # the amount of width reserved for blank space between subplots
    hspace = 0.2   # the amount of height reserved for white space between subplots
    

    实际默认值由rc文件控制

  • 27

    类似于 tight_layout matplotlib现在(从版本2.2开始)提供contrained_layout . 与 tight_layout (可能在代码中随时调用单个优化布局)相比, constrained_layout 是一个属性,可以处于活动状态,并在每个绘制步骤之前优化布局 .

    因此,需要在子图创建之前或期间激活它 . 这可能是 figure(contrained_layout=True)subplots(constrained_layout=True) 的参数 .

    例:

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(4,4, constrained_layout=True)
    
    plt.show()
    

    enter image description here

    也可以通过 rcParams 设置constrained_layout

    plt.rcParams['figure.constrained_layout.use'] = True
    

    what's new entryContrained Layout Guide

  • 14
    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(10,60))
    plt.subplots_adjust( ... )
    

    plt.subplots_adjust 方法:

    def subplots_adjust(*args, **kwargs):
        """
        call signature::
    
          subplots_adjust(left=None, bottom=None, right=None, top=None,
                          wspace=None, hspace=None)
    
        Tune the subplot layout via the
        :class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
        meanings (and suggested defaults) are::
    
          left  = 0.125  # the left side of the subplots of the figure
          right = 0.9    # the right side of the subplots of the figure
          bottom = 0.1   # the bottom of the subplots of the figure
          top = 0.9      # the top of the subplots of the figure
          wspace = 0.2   # the amount of width reserved for blank space between subplots
          hspace = 0.2   # the amount of height reserved for white space between subplots
    
        The actual defaults are controlled by the rc file
        """
        fig = gcf()
        fig.subplots_adjust(*args, **kwargs)
        draw_if_interactive()
    

    or

    fig = plt.figure(figsize=(10,60))
    fig.subplots_adjust( ... )
    

    图片的大小很重要 .

    “我已经尝试过使用hspace,但增加它似乎只会使所有图形更小而不解决重叠问题 . ”

    因此,为了产生更多的空白区域并保持子图的大小,总图像需要更大 .

  • 272

    尝试使用plt.tight_layout

    作为一个简单的例子:

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=4, ncols=4)
    fig.tight_layout() # Or equivalently,  "plt.tight_layout()"
    
    plt.show()
    

    没有紧密的布局

    enter image description here


    紧密布局
    enter image description here

  • 0

    我发现subplots_adjust(hspace = 0.001)最终为我工作了 . 当我使用space = None时,每个绘图之间仍然有空白 . 将它设置为非常接近于零但似乎迫使它们排成一行 . 我在这里上传的不是最优雅的代码,但你可以看到hspace的工作原理 .

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker as tic
    
    fig = plt.figure()
    
    x = np.arange(100)
    y = 3.*np.sin(x*2.*np.pi/100.)
    
    for i in range(5):
        temp = 510 + i
        ax = plt.subplot(temp)
        plt.plot(x,y)
        plt.subplots_adjust(hspace = .001)
        temp = tic.MaxNLocator(3)
        ax.yaxis.set_major_locator(temp)
        ax.set_xticklabels(())
        ax.title.set_visible(False)
    
    plt.show()
    

    enter image description here

相关问题