简体   繁体   English

imshow 子图在 matplotlib 图中的位置

[英]imshow subplot placement inside matplotlib figure

I have a Python script that draws a matrix of images, each image is read from disk and is 100x100 pixels.我有一个绘制图像矩阵的 Python 脚本,每个图像都是从磁盘读取的,大小为 100x100 像素。 Current result is:目前的结果是:

matrix of images图像矩阵

I don't know why Python adds vertical spacing between each row.我不知道为什么 Python 在每行之间添加垂直间距。 I tried setting several parameters for plt.subplots .我尝试为plt.subplots设置几个参数。 Rendering code is below:渲染代码如下:

fig, axs = plt.subplots(
    gridRows, gridCols, sharex=True, sharey=False, constrained_layout={'w_pad': 0, 'h_pad': 0, 'wspace': 0, 'hspace': 0}, figsize=(9,9)
)
k = 0

for i in range(len(axs)):
    for j in range(len(axs[i])):
        if (k < paramsCount and dataset.iat[k,2]):
            img = mpimg.imread(<some_folder_path>)
        else:
            img = mpimg.imread(<some_folder_path>)
            
        ax = axs[i, j]    
        ax.imshow(img)
        ax.axis('off')
        if (i == 0): ax.set_title(dataset.iat[k,1])
        if (j == 0): ax.text(-0.2, 0.5, dataset.iat[k,0], transform=ax.transAxes, verticalalignment='center', rotation='vertical', size=12)
        
        axi = ax.axis()
        rec = plt.Rectangle((axi[0], axi[2]), axi[1] - axi[0], axi[3] - axi[2], fill=False, lw=1, linestyle="dotted")
        rec = ax.add_patch(rec)
        rec.set_clip_on(False)

        k = k + 1

plt.show()

Desired result is like:期望的结果是这样的:

desired result期望的结果

Does anyone have ideas?有人有想法吗?

I'm sure there are many ways to do this other than the tashi answer, but the grid and subplot keywords are used in the subplot to remove the spacing and scale.我确信除了 tashi 答案之外还有很多方法可以做到这一点,但是在 subplot 中使用了 grid 和 subplot 关键字来删除间距和比例。 In the loop process for each subplot, I set the graph spacing, remove the tick labels, and adjust the spacing by making the border dashed and the color gray.在每个子图的循环过程中,我设置了图形间距,删除了刻度标签,并通过使边框虚线和灰色来调整间距。 The title and y-axis labels are also added based on the loop counter value.标题和 y 轴标签也根据循环计数器值添加。 Since the data was not provided, some of the data is written directly, so please replace it with your own data.由于没有提供数据,部分数据是直接写的,请用自己的数据替换。

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(20220510)
grid = np.random.rand(4, 4)
gridRows, gridCols = 5, 10
titles = np.arange(5,51,5)
ylabels = [500,400,300,200,100]
fig, axs = plt.subplots(gridRows, gridCols,
                        figsize=(8,4), 
                        gridspec_kw={'wspace':0, 'hspace':0},
                       subplot_kw={'xticks': [], 'yticks': []}
                       )

for i, ax in enumerate(axs.flat):
    ax.imshow(grid, interpolation='lanczos', cmap='viridis', aspect='auto')
    ax.margins(0, 0)
    if i < 10:
        ax.set_title(str(titles[i]))
    if i in [0,10,20,30,40]:
        ax.set_ylabel(ylabels[int(i/10)])
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    for s in ['bottom','top','left','right']:
        ax.spines[s].set_linestyle('dashed')
        ax.spines[s].set_capstyle("butt")
    for spine in ax.spines.values():
        spine.set_edgecolor('gray')

plt.show()

在此处输入图像描述

I realized it has to do with the dimensions passed to figsize .我意识到这与传递给figsize的尺寸有关。 Since rows count is half the columns count, I need to pass figsize(width, width/2) .由于行数是列数的一半,我需要通过figsize(width, width/2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM