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

Improve subplot size/spacing with many subplots in matplotlib

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

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

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

我的代码目前看起来像

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

尝试使用plt.tight_layout

作为一个简单的例子:

1
2
3
4
5
6
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


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

通话签名:

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

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

1
2
3
4
5
6
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文件控制


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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


1
2
3
4
import matplotlib.pyplot as plt

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

plt.subplots_adjust方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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()

要么

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

图片的大小很重要。

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

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


你可以试试subplot_tool()

1
plt.subplot_tool()


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

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

例:

1
2
3
4
5
import matplotlib.pyplot as plt

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

plt.show()

enter image description here

constrained_layout也可以通过rcParams设置

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

请参阅新条目和"约束布局指南"