matplotlib图中的imshow子图位置

发布于 2025-01-27 23:31:01 字数 1334 浏览 4 评论 0原文

我有一个python脚本绘制图像矩阵,每个图像都是从磁盘读取的,是100x100像素。当前结果是:

图像矩阵

我不知道为什么python在每行之间添加垂直间隔。我尝试为plt.subplots设置多个参数。渲染代码如下:

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()

所需结果类似于:

所需的结果

有人有想法吗?

I have a Python script that draws a matrix of images, each image is read from disk and is 100x100 pixels. Current result is:

matrix of images

I don't know why Python adds vertical spacing between each row. I tried setting several parameters for 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹤舞 2025-02-03 23:31:01

我敢肯定,除了tashi答案外,还有很多方法可以做到这一点,但是在子图中使用网格和子图关键字来删除间距和规模。在每个子图的循环过程中,我设置了图形间距,卸下刻度标签,并通过使边框虚线和颜色为灰色来调整间距。标题和Y轴标签还基于循环计数器值添加。由于未提供数据,因此某些数据是直接编写的,因此请用自己的数据替换。

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'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. 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. 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()

enter image description here

如果没有你 2025-02-03 23:31:01

我意识到这与传递给无花果的尺寸有关。由于行计数是列数的一半,因此我需要通过firfigsize(宽度,宽度/2)

I realized it has to do with the dimensions passed to figsize. Since rows count is half the columns count, I need to pass figsize(width, width/2).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文