通过matplotlib中的许多子图来改善子图大小/间距

问题:通过matplotlib中的许多子图来改善子图大小/间距

这个问题非常相似,但不同之处在于我的身材可以达到所需的大小。

我需要在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)

Very similar to this question but with the difference that my figure can be as large as it needs to be.

I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using figsave and viewed on a webpage, so I don’t care how tall the final image is as long as the subplots are spaced so they don’t overlap.

No matter how big I allow the figure to be, the subplots always seem to overlap.

My code currently looks like

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)

回答 0

尝试使用 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()

没有紧凑的布局


布局紧凑

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Without Tight Layout


With Tight Layout


回答 1

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

通话签名:

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文件控制

You can use plt.subplots_adjust to change the spacing between the subplots (source)

call signature:

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

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


回答 2

我发现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()

I found that subplots_adjust(hspace = 0.001) is what ended up working for me. When I use space = None, there is still white space between each plot. Setting it to something very close to zero however seems to force them to line up. What I’ve uploaded here isn’t the most elegant piece of code, but you can see how the hspace works.

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()


回答 3

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()

要么

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

图片的大小很重要。

“我曾尝试将hspace弄乱,但增加它似乎只会使所有图变小,而无法解决重叠问题。”

因此,为了获得更多的空白并保持子图的大小,总图像需要更大。

import matplotlib.pyplot as plt

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

The plt.subplots_adjust method:

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( ... )

The size of the picture matters.

“I’ve tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem.”

Thus to make more white space and keep the sub plot size the total image needs to be bigger.


回答 4

您可以尝试subplot_tool()

plt.subplot_tool()

You could try the subplot_tool()

plt.subplot_tool()

回答 5

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

因此,需要在创建子图之前或期间激活它,例如figure(constrained_layout=True)subplots(constrained_layout=True)

例:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(4,4, constrained_layout=True)

plt.show()

constrained_layout也可以通过 rcParams

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

查看新增内容和《受限布局指南》

Similar to tight_layout matplotlib now (as of version 2.2) provides constrained_layout. In contrast to tight_layout, which may be called any time in the code for a single optimized layout, constrained_layout is a property, which may be active and will optimze the layout before every drawing step.

Hence it needs to be activated before or during subplot creation, such as figure(constrained_layout=True) or subplots(constrained_layout=True).

Example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(4,4, constrained_layout=True)

plt.show()

constrained_layout may as well be set via rcParams

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

See the what’s new entry and the Constrained Layout Guide