python - 子图边距以适合 matplotlib 中的标题和标签

标签 python matplotlib margins

我阅读了大量有关类似问题的答案,但没有一个有帮助。

我只是想增加子图与顶部、左侧和底部边缘之间的边距,以适应 fig.suptitle 以及常见的 xlabel 和 ylabel。

import matplotlib.pyplot as plt
import random

#from matplotlib import rcParams
#rcParams['axes.titlepad'] = 20 # kind of works but shifts all titles, not only suptitle

def dummy(n):
    return random.sample(range(1, 100), n)


data = dict()
for i in range(4):
    data["area{}".format(i)] = [dummy(10), dummy(10)]

fig, ax = plt.subplots(2, 2, sharex='all', sharey='all', figsize=(10, 10))
fig.suptitle("Common title", fontsize=22)

ax = ax.reshape(-1)
for i, (area, data) in enumerate(data.items()):
    ax[i].set_title(area)
    ax[i].scatter(data[0], data[1])

fig.text(0.5, 0.01, 'xlabel', ha='center', fontsize=15)
fig.text(0.01, 0.5, 'ylabel', va='center', fontsize=15, rotation=90)

fig.tight_layout() # Does nothing
fig.subplots_adjust(top=0.85) # Does nothing
fig.show()

Matplotlib 版本 3.0.0

Python 3.6.6

Example plot from shared code

最佳答案

有很多方法可以处理这个问题,但我建议使用 gridspec_kw 输入到 plt.subplots 来实现此目的。 gridspec_kw 的文档基本上就是 gridspec.GridSpec文档。例如:

fig, ax = plt.subplots(2, 2, sharex='all', sharey='all',
                       gridspec_kw=dict(left=0.1, right=0.9,
                                        bottom=0.1, top=0.9),
                       figsize=(10, 10))

leftright、...gridspec_kw 的输入指定整个子图组的范围。

这能满足您的需求吗?

关于python - 子图边距以适合 matplotlib 中的标题和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697582/

相关文章:

svg - 如何在 nvd3 图表中添加边距

CSS 2.1 规范 : rationale for not collapsing margins of parent (when parent is float or has overflow other than visible)

python - 多指标箱线图

python - Matplotlib 是否向我们的命名空间添加变量以及它如何存储数据?

Python - 分发带有源代码的库

python - 分配给 pandas DataFrame 中的新列时令人费解的 KeyError

python - 一个步骤的 Matplotlib 动画

jquery - 如何让这个 jQuery 动画函数从下到上工作?

python - 在 blobstore 中更新和保存现有的 blob/文件?

python - 2个字符串之间的删除距离