繁体   English   中英

如何使 pyplot.subplots 中的图像变大

[英]How to make image inside pyplot.subplots larger

我需要在网格中显示20张图片,我的代码如下

def plot_matric_demo(img, nrows, ncols):
    fig, ax = plt.subplots(nrows=nrows, ncols=ncols)
    cur_index = 0
    for row in ax:
        for col in row:
            col.imshow(img)
            cur_index = cur_index + 1
            col.axis('off')

    plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
    plt.show()

subplot_img = cv2.imread("subplots.png")
plot_matric_demo(subplot_img, 5, 4)

貌似子图中的图像太小了,同时距离又大了,我想知道如何让子图中的图像变大?

在此处输入图像描述

TL;DR使用plt.subplots(nrows=nr, ncols=nc, figsize=(..., ...))来调整图形大小,以便各个子图至少大致具有相同的纵横比要显示的图像。


关键是, imshow将使用正方形像素,因此如果您的图像具有 1:2 的纵横比,则绘制的图像将具有 1:2 的纵横比,并且每个图像都将位于其自己的子图的中间——如果子图的纵横比与图像的纵横比不同,您将遇到“大白边综合症”。

让我们从导入和假图像开始,纵横比为 1:2

 In [1]: import numpy as np 
   ...: import matplotlib.pyplot as plt                                                   

In [2]: img = np.arange(54*108).reshape(108,54)                                           

并复制您的安排,其中您将 8x6 (x:y) 图形细分为 4x5 (x:y) 子图 - 您有水平宽 (8/4=2) 和垂直短 (6/5=1.2) 的子图每个图像在其子图中居中时,都有一个 WIDE 水平边距。

In [3]: f, axs = plt.subplots(5, 4) 
   ...: for x in axs.flatten(): 
   ...:     x.imshow(img) ; x.axis('off')                                                 

在此处输入图像描述

现在恢复行和列的作用,现在你的子图在水平方向上更小 (8/5=1.6) 而更高 (6/4=1.5),由于水平白边距的减少和图像大小,因为可用高度更大

In [4]: f, axs = plt.subplots(4, 5) 
   ...: for x in axs.flatten(): 
   ...:     x.imshow(img) ; x.axis('off')                                                 

在此处输入图像描述

为了结束这个故事,关键是让子图具有(至少近似)与您使用的图像相同的纵横比,为此我们必须干预figsize参数,分配一个 width:height 是等于 (ncols×1):(nrows×2),在我下面的例子中figsize=(5,8)

In [5]: f, axs = plt.subplots(4, 5, figsize=(5,8)) 
   ...: for x in axs.flatten(): 
   ...:     x.imshow(img) ; x.axis('off')                                                 

在此处输入图像描述

暂无
暂无

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

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