单个窗口中的多个数字

blu*_*fer 7 python image matplotlib subplot

我想创建一个功能,在一个窗口中在屏幕上绘制一组图形.到现在为止我写这段代码:

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')
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我想有选择在单个窗口中绘制所有数字.而这段代码没有.我读了一些关于subplot的东西,但看起来很棘手.

gca*_*tes 11

您可以根据子图命令定义一个函数(注意结尾处的s,与subploturinieto指向的命令不同)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
Run Code Online (Sandbox Code Playgroud)

基本上,该函数根据所需的行数(nrows)和列数(ncols)创建图中的多个轴,然后遍历轴列表以绘制图像并为每个轴添加标题.

请注意,如果您的字典中只有一个图像,那么之前的语法plot_figures(figures)将起作用,nrows并且默认ncols设置为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)
Run Code Online (Sandbox Code Playgroud)

前

  • 只是在可读性上有一点改进:将 `zip(range(len(figures)), numbers)` 替换为 `enumerate(figures)` (3认同)