单个窗口中的多个图形

22

我想创建一个函数,在一个窗口中画出一组图形。目前,我写了以下代码:

import pylab as pl

def plot_figures(figures):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary

    """
    for title in figures:
        pl.figure()
        pl.imshow(figures[title])
        pl.gray()
        pl.title(title)
        pl.axis('off')

它能够完美运行,但我希望有一个选项可以在单个窗口中绘制所有图形。但是这段代码不能做到。我读了一些关于subplot的东西,但看起来很棘手。


您也可以通过skimage使用montage函数。https://stackoverflow.com/a/65033307/11143105 - Operator77
7个回答

21
你可以根据 subplots 命令(注意末尾的 s ,与 urinieto 指向的subplot 命令不同)在 matplotlib.pyplot 中定义一个函数。
以下是一个基于你的示例的这样的函数示例,允许在一个图中绘制多个坐标轴。您可以在图布局中定义想要的行数和列数。
def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in enumerate(figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.gray())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional

这个函数会根据你想要的行数 (nrows) 和列数 (ncols) 在图形中创建多个轴,然后遍历轴列表以绘制你的图像并为每个图像添加标题。

请注意,如果你的字典中只有一张图片,你之前的语法 plot_figures(figures) 将会起作用,因为默认情况下 nrowsncols 均设置为 1

以下是一个示例:

import matplotlib.pyplot as plt
import numpy as np

# generation of a dictionary of (title, images)
number_of_im = 6
figures = {'im'+str(i): np.random.randn(100, 100) for i in range(number_of_im)}

# plot of the images in a figure, with 2 rows and 3 columns
plot_figures(figures, 2, 3)

ex


(该内容为一段HTML代码,其中包含一个图片标签,图片的来源是"https://i.imgur.com/pxiC8.png",并且在该图片无法显示时会显示“ex”的代替文本)

3
提高可读性的一点小改进:将zip(range(len(figures)), figures)替换为enumerate(figures) - Hemerson Tacon

2
你应该使用 subplot
在你的情况下,如果你想要它们一个在另一个上面,就像这样:
fig = pl.figure(1)
k = 1
for title in figures:
    ax = fig.add_subplot(len(figures),1,k)
    ax.imshow(figures[title])
    ax.gray()
    ax.title(title)
    ax.axis('off')
    k += 1

请查看文档了解其他选项。


0
import numpy as np

def save_image(data, ws=0.1, hs=0.1, sn='save_name'):
    import matplotlib.pyplot as plt
    m = n = int(np.sqrt(data.shape[0])) # (36, 1, 32, 32)

    fig, ax = plt.subplots(m,n, figsize=(m*6,n*6))
    ax = ax.ravel()
    for i in range(data.shape[0]):
        ax[i].matshow(data[i,0,:,:])
        ax[i].set_xticks([])
        ax[i].set_yticks([])

    plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, 
                        top=0.9, wspace=ws, hspace=hs)
    plt.tight_layout()
    plt.savefig('{}.png'.format(sn))

data = np.load('img_test.npy')

save_image(data, ws=0.1, hs=0.1, sn='multiple_plot')

enter image description here


0
def plot_figures(figures, nrows=None, ncols=None):
    if not nrows or not ncols:
        # Plot figures in a single row if grid not specified
        nrows = 1
        ncols = len(figures)
    else:
        # check minimum grid configured
        if len(figures) > nrows * ncols:
            raise ValueError(f"Too few subplots ({nrows*ncols}) specified for ({len(figures)}) figures.")

    fig = plt.figure()

    # optional spacing between figures
    fig.subplots_adjust(hspace=0.4, wspace=0.4)

    for index, title in enumerate(figures):
        plt.subplot(nrows, ncols, index + 1)
        plt.title(title)
        plt.imshow(figures[title])
    plt.show()

只要行数和列数的乘积大于或等于图形数量,任何网格配置(或无配置)都可以指定。

例如,对于len(figures) == 10,以下是可接受的:

plot_figures(figures)
plot_figures(figures, 2, 5)
plot_figures(figures, 3, 4)
plot_figures(figures, 4, 3)
plot_figures(figures, 5, 2)


0

如何正确地显示多个图像在一个图中?的答案基础上,这里提供另一种方法:

import math
import numpy as np
import matplotlib.pyplot as plt

def plot_images(np_images, titles = [], columns = 5, figure_size = (24, 18)):
    count = np_images.shape[0]
    rows = math.ceil(count / columns)

    fig = plt.figure(figsize=figure_size)
    subplots = []
    for index in range(count):
        subplots.append(fig.add_subplot(rows, columns, index + 1))
        if len(titles):
            subplots[-1].set_title(str(titles[index]))
        plt.imshow(np_images[index])

    plt.show()

0

你也可以这样做:

import matplotlib.pyplot as plt

f, axarr = plt.subplots(1, len(imgs))
for i, img in enumerate(imgs):
    axarr[i].imshow(img)

plt.suptitle("Your title!")
plt.show()

0
如果您想将多个图形分组到一个窗口中,可以像这样操作:
import matplotlib.pyplot as plt
import numpy as np


img = plt.imread('C:/.../Download.jpg') # Path to image
img = img[0:150,50:200,0] # Define image size to be square --> Or what ever shape you want

fig = plt.figure()

nrows = 10 # Define number of columns
ncols = 10 # Define number of rows
image_heigt = 150 # Height of the image
image_width = 150 # Width of the image


pixels = np.zeros((nrows*image_heigt,ncols*image_width)) # Create 
for a in range(nrows):
    for b in range(ncols):
        pixels[a*image_heigt:a*image_heigt+image_heigt,b*image_heigt:b*image_heigt+image_heigt] = img
plt.imshow(pixels,cmap='jet')
plt.axis('off')
plt.show()

作为结果,您将收到: 在此输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接