我试图在一张图上显示20个随机图像。确实显示了图像,但它们被覆盖。我正在使用:
import numpy as np
import matplotlib.pyplot as plt
w=10
h=10
fig=plt.figure()
for i in range(1,20):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(i,2,1)
plt.imshow(img)
plt.show()
我希望它们自然地出现在网格布局中(比如4x5),每个都有相同的大小。部分问题是我不知道add_subplot的参数是什么意思。文档声明参数是行数,列数和图号。没有定位论点。此外,图号只能是1或2.我怎样才能实现这个目标?
答案 0 :(得分:106)
以下是我可以尝试的方法:
USE LISTS
USE LINKEDLIST_ROUTINES
#include "macros.h"
IMPLICIT NONE
PRIVATE
结果图片:
(原答复日期:17年10月7日4:20)
修改1
因为这个答案很受欢迎,超出了我的预期。我发现需要做一些小改动才能灵活地操纵各个地块。所以我将这个新版本提供给原始代码。 实质上,它提供: -
新代码:
import numpy as np
import matplotlib.pyplot as plt
w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
结果图:
修改2
在前面的示例中,代码提供了对具有单个索引的子图的访问,这在图具有许多行/列子图时是不方便的。这是它的替代品。下面的代码提供了使用import numpy as np
import matplotlib.pyplot as plt
w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5
# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# ax enables access to manipulate each of subplots
ax = []
for i in range(columns*rows):
img = np.random.randint(10, size=(h,w))
# create subplot and append to ax
ax.append( fig.add_subplot(rows, columns, i+1) )
ax[-1].set_title("ax:"+str(i)) # set title
plt.imshow(img, alpha=0.25)
# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)
plt.show() # finally, render the plot
的子图的访问,这更适合于操纵许多子图的数组。
[row_index][column_index]
结果图:
答案 1 :(得分:2)
您可以尝试以下方法:
import matplotlib.pyplot as plt
import numpy as np
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 zip(range(len(figures)), figures):
axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
axeslist.ravel()[ind].set_title(title)
axeslist.ravel()[ind].set_axis_off()
plt.tight_layout() # optional
# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}
# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)
plt.show()
但是,这基本上只是从这里复制和粘贴:Multiple figures in a single window因此该帖子应该被认为是重复的。
我希望这会有所帮助。