首页 > 解决方案 > 子图之间的 Matplotlib 距离

问题描述

我有 3x3matplotlib轴,其中包含sns.heatmap. 在主热图的左侧和上方ax[1][1](即 2D 矩形,例如形状为 10x25 )放置了两个额外的热图(例如 10x1 和 1x25)。

主热图与其他两个之间的距离取决于主热图内容的形状[0]和形状[1]的比例......

我还没有找到保持它不变的方法,所以如果我尝试绘制一个尺寸不成比例的数组(比如 50 x 10),其中一个距离会变得高得离谱:(

这个https://ibb.co/rx9DRgp图像显示了由以下代码产生的不相等的 x 和 y 距离,这说明了这个问题......

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns

YZ = np.random.normal(loc=0.0, scale=1.0, size=(10,25))
XB = np.random.normal(loc=0.0, scale=1.0, size=(25,1))
XA = np.random.normal(loc=0.0, scale=1.0, size=(10,1))

fig, ax = plt.subplots(
    3,3,
    figsize=( YZ.shape[1], YZ.shape[0], ),
    gridspec_kw={
        "width_ratios"  : [ 1, YZ.shape[1], 0.5 ],
        "height_ratios" : [ 1, YZ.shape[0], 0.5 ],
    }
)

with sns.axes_style("darkgrid"):
    hm = {}; hm[0],hm[1],hm[2] = {},{},{}
    hm[1][1] = sns.heatmap(
        data       = YZ,
        ax         = ax[1][1],
        square     = True,
        annot_kws  = {"size": 8},
        linewidths = 0,
        cbar       = True,
        cbar_ax    = ax[1][2],
    )
    hm[1][0] = sns.heatmap(
        data       = XA,
        ax         = ax[1][0],
        square     = True,
        annot_kws  = {"size": 8},
        linewidths = 2,
        linecolor  = "white",
        cbar       = False,
    )
    hm[0][1] = sns.heatmap(
        data       = XB.T,
        ax         = ax[0][1],
        square     = True,
        annot_kws  = {"size": 8},
        linewidths = 2,
        linecolor  = "white",
        cbar       = False,
    )
ax[1][1].get_shared_x_axes().join( ax[1][1], ax[0][1] )
ax[1][1].get_shared_y_axes().join( ax[1][1], ax[1][0] )
plt.tight_layout()
plt.show()

有没有一种简单的方法可以使两个轴之间的距离保持不变(比如图像宽度的 10% 或 200px)

我不知道如何使和之间的距离与和ax[1][1]之间的距离ax[1][0]相同......ax[1][1]ax[0][1]

标签: pythonmatplotlibseaborn

解决方案


推荐阅读