单个窗口中的多个图形

新手上路,请多包涵

我想创建一个函数,在屏幕上的单个窗口中绘制一组图形。现在我写了这段代码:

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

它工作得很好,但我希望可以选择在单个窗口中绘制所有图形。而这段代码没有。我读了一些关于子图的东西,但它看起来很棘手。

原文由 blueSurfer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 599
2 个回答

您可以根据 --- 的 subplots 命令(注意最后的 s ,不同于 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 )在图中创建多个轴,然后遍历轴列表绘制图像并为每个图像添加标题。

Note that if you only have one image in your dictionary, your previous syntax plot_figures(figures) will work since nrows and ncols are set to 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)

前任

原文由 gcalmettes 发布,翻译遵循 CC BY-SA 4.0 许可协议

您应该使用 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

查看其他选项的 文档

原文由 Oriol Nieto 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题