单个窗口中的多个数字 [英] Multiple figures in a single window
问题描述
我想创建一个功能,在一个窗口中在屏幕上绘制一组图形。到现在为止我编写了这段代码:
I want to create a function which plot on screen a set of figures in a single window. By now I write this code:
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的内容,但看起来很棘手。
It works perfectly but I would like to have the option for plotting all the figures in single window. And this code doesn't. I read something about subplot but it looks quite tricky.
推荐答案
你可以根据 subplots 命令(注意 s 最后,不同于 matplotlib.pyplot
的 matplotlib.pyplot
指定的子图
命令。
You can define a function based on the subplots command (note the s at the end, different from the subplot
command pointed by urinieto) of matplotlib.pyplot
.
以下是基于您的此类函数的示例,允许在图中绘制多个轴。您可以在图布局中定义所需的行数和列数。
Below is an example of such a function, based on yours, allowing to plot multiples axes in a figure. You can define the number of rows and columns you want in the figure layout.
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
),然后迭代列表用于绘制图像的轴并为每个图像添加标题。
Basically, the function creates a number of axes in the figures, according to the number of rows (nrows
) and columns (ncols
) you want, and then iterates over the list of axis to plot your images and adds the title for each of them.
请注意,如果字典中只有一个图像,则以前的语法 plot_figures(数字)
将自 nrows
和 ncols
设置为 1
默认情况下。
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
by default.
您可以获得的一个示例:
An example of what you can obtain:
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)
这篇关于单个窗口中的多个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!