python - Matplotlib 子图太窄且布局紧凑

标签 python matplotlib subplot

我目前正在尝试使用 GridSpec 在 Matplotlib(Python 3.6、Matplotlib 2.0.0)中绘制许多子图。这是最小的工作示例:

import matplotlib.pyplot as plt
from matplotlib.gridspec import *

# Color vector for scatter plot points
preds = np.random.randint(2, size=100000)

# Setup the scatter plots
fig = plt.figure(figsize=(8,8))
grid = GridSpec(9, 9)

# Create the scatter plots
for ii in np.arange(0, 9):
    for jj in np.arange(0, 9):
        if (ii > jj):
            ax = fig.add_subplot(grid[ii, jj])
            x = np.random.rand(100000)*2000
            y = np.random.rand(100000)*2000
            ax.scatter(x, y, c=preds)

这是没有任何修改的结果:

enter image description here

当然,子图之间的间距并不令人满意,所以我做了我通常做的事情并使用了tight_layout()。但如下图所示,tight_layout() 挤压了图的宽度,令人无法接受:

Figure With Tight Layout

我认为我应该使用subplots_adjust()手动调整子图,而不是使用tight_layout()。下图是带有 subplots_adjust(hspace=1.0, wspace=1.0) 的图。

Figure With Manually Adjusted Subplots

结果几乎是正确的,如果稍微调整一下子图之间的空间就会很完美。然而,子图看起来太小,无法充分传达信息。

有没有更好的方法可以在子图之间获得适当的间距,同时仍然保持纵横比和足够大的子图尺寸?我能想到的唯一可能的解决方案是使用 subplots_adjust() 和更大的 figsize,但这会导致图形边缘和图形边缘之间的空间非常大。次要情节。

任何解决方案都值得赞赏。

最佳答案

由于所有轴都具有相同的 xy 范围,我会选择仅在外部上显示刻度标签。对于大小相等的子图网格,可以使用 plt.subplots()sharexsharey 关键字轻松实现自动化。当然,如果您设置了 9x9 子图的网格,则会提供比您想要的更多的图,但您可以使冗余图不可见(例如使用 Axes.set_visible 或完全删除它们)。在下面的示例中,我选择后者。

from matplotlib import pyplot as plt
import numpy as np

fig, axes = plt.subplots(
    nrows=9, ncols=9, sharex=True, sharey=True, figsize = (8,8)
)

# Color vector for scatter plot points
preds = np.random.randint(2, size=1000)

# Create the scatter plots
for ii in np.arange(0, 9):
    for jj in np.arange(0, 9):
        if (ii > jj):
            ax = axes[ii,jj]
            x = np.random.rand(1000)*100
            y = np.random.rand(1000)*2000
            ax.scatter(x, y, c=preds)
        else:
            axes[ii,jj].remove() ##remove Axes from fig
            axes[ii,jj] = None   ##make sure that there are no 'dangling' references.    

plt.show()

结果如下所示:

result of the above code

当然可以使用 subplots_adjust() 之类的方法进一步调整。希望这会有所帮助。

关于python - Matplotlib 子图太窄且布局紧凑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201514/

相关文章:

python - Matplotlib:如何调整第二个图例的 zorder?

python - python 中有语音到文本转换库或 api 吗?

python - 为什么在类上设置描述符会覆盖描述符?

python - 安装后没有名为 matplotlib 的模块

matplotlib - 在python中将矩阵绘制为表格

matplotlib - 在 matplotlib 的子图中嵌入小图

python - 将 pandas DataFrame 图插入 matplotlib 子图中

matlab - 交换图中的子图

python - 创建具有特定布局、部分的列表

python - 覆盖变量时 Python 中的内存位置会发生什么变化?