I'm trying to create a 4x2 plot on a slightly non-rectangular dataset (x-axis range is smaller than y-axis range) using plt.subplots and assign colorbars using make_axes_locatable to have the colorbars nice and flush wih the subplots. I always end up with huge paddings/margins between the two subplot columns which I suspect originate from the colorbars... I've tried multiple things from many stackoverflow questions (e.g. using fig.subplots_adjust(), constrained_layout=True etc.) but to no avail. The margins between the two columns stay really large (see img below) and make the image unreadable... enter image description here Any input would be much appreciated! Code used to reproduce the issue:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

data = np.random.random((10, 6))

fig, axs = plt.subplots(nrows=4, ncols=2, figsize=(16, 8), sharex=True, sharey=False, constrained_layout=True)
for idx in range(4):
    # plot image
    im1 = axs[idx, 0].imshow(data, cmap=cm.coolwarm)
    im2 = axs[idx, 1].imshow(data, cmap=cm.viridis)
    # make colorbars
    ax1_divider = make_axes_locatable(axs[idx, 0])
    cax1 = ax1_divider.append_axes("right", size="2%", pad=0.05)
    cb1 = fig.colorbar(im1, cax=cax1, orientation="vertical")
    ax2_divider = make_axes_locatable(axs[idx, 1])
    cax2 = ax2_divider.append_axes("right", size="2%", pad=0.05)
    cb2 = fig.colorbar(im2, cax=cax2, orientation="vertical")

推荐答案

您正在打印多个图像(默认情况下,它会try 保持相等的纵横比),其中高度大于宽度.因此,图像的总高度>;图像的总宽度.

因此,减少列之间白色间距的一种方法是减少图形的宽度.

try 设置:

fig, axs = plt.subplots(nrows=4, ncols=2, figsize=(4, 8), sharex=True, sharey=False, constrained_layout=True)

Python相关问答推荐

Python:记录而不是在文件中写入询问在多文件项目中记录的最佳实践

指示组内的rejected_time是否在creation_timestamp后5分钟内

在上下文管理器中更改异常类型

在应用循环中间保存pandas DataFrame

仿制药的类型铸造

对某些列的总数进行民意调查,但不单独列出每列

Pytest两个具有无限循环和await命令的Deliverc函数

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

Pandas 有条件轮班操作

不理解Value错误:在Python中使用迭代对象设置时必须具有相等的len键和值

如何从具有不同len的列表字典中创建摘要表?

加速Python循环

如何使用它?

基于索引值的Pandas DataFrame条件填充

在单次扫描中创建列表

将一个双框爆炸到另一个双框的范围内

在Django中重命名我的表后,旧表中的项目不会被移动或删除

提取最内层嵌套链接

ModuleNotFoundError:Python中没有名为google的模块''

来自Airflow Connection的额外参数