【问题标题】:Subplots margins to fit title and labels in matplotlib子图边距以适合 matplotlib 中的标题和标签
【发布时间】:2019-02-14 19:15:40
【问题描述】:

我已经阅读了大量关于类似问题的答案,但没有任何帮助。

我只想增加子图与顶部、左侧和底部边缘之间的边距,以适应 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

【问题讨论】:

  • 能否请您发布您的 matplotlib 版本?
  • 尝试注释掉fig.tight_layout()
  • @DanielLabbe 完成 :)
  • @Bazingaa,我已经做到了,无论我是否包含它,它都没有区别。
  • 请注意,fig.subplots_adjust(top=0.85) 应该并且确实是work fine。因此,您的案例可能有一些特殊之处,涉及正在使用的 matplotlib 版本或运行代码的环境。

标签: python matplotlib margins


【解决方案1】:

有很多方法可以处理这个问题,但我建议为此使用gridspec_kw 输入到plt.subplotsgridspec_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))

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

这能满足您的需求吗?

【讨论】:

  • 天哪,这太完美了!非常感谢!
  • hspacewspace 也可以控制子图之间的间距
猜你喜欢
  • 2011-11-23
  • 2021-01-11
  • 1970-01-01
  • 2014-11-06
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 2015-04-09
相关资源
最近更新 更多