Featured image of post Draw Subfig and making subplot.md

Draw Subfig and making subplot.md

绘制子图来批量浏览图像

创建子图来进行图像浏览,灵活性很强,但是经常忘记怎么用,这里特意写一个博客,来强化一下记忆。

绘制子图

首先,在某个位置绘制子图,需要调用 plt.subplot 方法。

1
2
3
import matplotlib.pyplot as plt

plt.subplot(nrows, ncols, index)

分别是行列以及子图编号。我之前经常不记得 index 是子图编号。

在绘制子图之前,首先要创建子图。

1
2
# 创建子图
plt.figure(figsize=(10, 6))

例子

接下来, 是一个完整的例子。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import matplotlib.pyplot as plt
import numpy as np

# 创建数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# 创建子图
plt.figure(figsize=(10, 6))

# 第一个子图
plt.subplot(2, 2, 1)  # 2行2列的第1个
plt.plot(x, y1, label="sin(x)")
plt.title("Sine Wave")
plt.legend()

# 第二个子图
plt.subplot(2, 2, 2)  # 2行2列的第2个
plt.plot(x, y2, label="cos(x)")
plt.title("Cosine Wave")
plt.legend()

# 第三个子图
plt.subplot(2, 2, 3)  # 2行2列的第3个
plt.plot(x, y3, label="tan(x)")
plt.title("Tangent Wave")
plt.legend()

# 第四个子图
plt.subplot(2, 2, 4)  # 2行2列的第4个
plt.plot(x, y1 + y2, label="sin(x) + cos(x)")
plt.title("Sum of Sine and Cosine")
plt.legend()

# 显示图形
plt.tight_layout()  # 自动调整子图间距
plt.show()

效果图

如果想要查看 (32, 1, 192, 32) shape 的图像,实际上还可以使用 torchvision 提供的工具函数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import torchvision.utils as vutils

# 将图片制作成网格
grid_img = vutils.make_grid(x, nrow=4, padding=2)

# 可视化网格图片
plt.figure(figsize=(10, 10))
plt.imshow(grid_img.permute(1, 2, 0))  # 调整通道顺序以适应 matplotlib 的要求
plt.axis('off')
plt.show()j
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计