Matplotlib 绘图不符合图形尺寸

问题描述 投票:0回答:1

我正在尝试使用特定大小的 GridSpec 方法创建一个带有子图的图形。我试图指定的尺寸是 4.205 x 2.2752 英寸,以适合学术人物中的面板。我使用Fig.subplots_adjust让子图填充整个图形。然而,输出图形具有完全不同的尺寸。这是我的代码:

# set up the figure
fig = plt.figure(figsize = (4.2055, 2.2752))

# number of columns in the Gridspec
fwid = 22

# set up the grid
grid = plt.GridSpec(1,fwid)

# set up the number of columns allocated to each subplot
h0 = int((fwid-1)/3)
h1 = int(h0*2)
ax = [
    fig.add_subplot(grid[:h0]),
    fig.add_subplot(grid[h0:h1]),
    fig.add_subplot(grid[h1]),
]


hm1 = np.random.randn(10,10)
hm2 = np.random.randn(10,10)

# plot the heatmaps
sns.heatmap(
    hm1, ax = ax[0],
    vmin = 0, vmax = 1,
    cbar = False
)
sns.heatmap(
    hm2, ax = ax[1],
    vmin = 0, vmax = 1,
    # put the colorbar in the 3rd subplot
    cbar_ax = ax[2]
)


ax[0].set_xticks(np.arange(0.5,10))
ax[0].set_xticklabels(np.arange(0.5,10))
ax[0].set_yticks(np.arange(0.5,10))
ax[1].set_yticks([])
ax[1].set_xticks(np.arange(0.5, 10))
ax[1].set_xticklabels(np.arange(0.5,10))

fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 1)

plt.savefig('example.png', facecolor = 'white', transparent = False,
            bbox_inches = 'tight', dpi = 300)

输出图如下所示:

不是 4.205 x 2.2752 英寸,而是 2.96 x 2.3166 英寸。不知道这里发生了什么。如有任何帮助,我们将不胜感激!

python matplotlib seaborn heatmap figsize
1个回答
0
投票

在初始图形实例化期间显式设置 DPI,以确保 Matplotlib
GridSpec
子图中的图形尺寸。

还必须实施一些小的额外更改(参见下面的代码)。

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns


# Set up the figure with a specific DPI
fig = plt.figure(figsize=(4.2055, 2.2752), dpi=300)

# Number of columns in the Gridspec
fwid = 22

# Set up the grid
grid = gridspec.GridSpec(1, fwid)

# Set up the number of columns allocated to each subplot
h0 = int((fwid - 1) / 3)
h1 = int(h0 * 2)
ax = [
    fig.add_subplot(grid[:h0]),
    fig.add_subplot(grid[h0:h1]),
    fig.add_subplot(grid[h1]),
]

hm1 = np.random.randn(10, 10)
hm2 = np.random.randn(10, 10)

sns.heatmap(
    hm1, ax=ax[0], vmin=0, vmax=1, cbar=False,
)
sns.heatmap(
    hm2, ax=ax[1], vmin=0, vmax=1, cbar_ax=ax[2],
)

ax[0].set_title("Heatmap 1")
ax[1].set_title("Heatmap 2")
ax[0].set_ylabel("Y Axis Label")

# Move the x-axis label downwards and adjust its position
ax[1].set_xlabel("X Axis Label", labelpad=15)
ax[1].xaxis.set_label_coords(0, -0.15)

# Remove y-axis tick labels for the second heatmap
ax[1].set_yticks([])

# Decrease axes tick labels font size for better readability
for a in ax:
    a.tick_params(axis="both", which="major", labelsize=6)

# Adjust the figure margins and size
plt.subplots_adjust(left=0.1, right=0.9, bottom=0.15, top=0.85)

plt.savefig(
    "example.png",
    facecolor="white",
    transparent=False,
    bbox_inches="tight",
    dpi=300,
)

产生:

在标准打印机纸张字母尺寸布局(8.5 x 11 英寸)上显示相同的输出,以显示生成的图形的英寸比例(我在 Photoshop 中测量的虚线边界框是您为面板尺寸指定的精确尺寸: 4.205 x 2.275 英寸 - 希望您了解如何根据需要自定义下面的代码):

© www.soinside.com 2019 - 2024. All rights reserved.