matplotlib显示多张图片
时间: 2023-10-10 16:09:43 浏览: 82
可以使用subplot()函数,它可以将多个图像放置在一张画布上。
示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.arange(0, 2 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# 创建画布
fig = plt.figure()
# 绘制第一个图像
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, y_sin)
ax1.set_title('Sine')
# 绘制第二个图像
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, y_cos)
ax2.set_title('Cosine')
# 显示图像
plt.show()
```
这个例子中,我们创建了一个包含两个图像的画布,第一个图像是正弦函数的图像,第二个图像是余弦函数的图像。subplot()函数的参数是三个整数,分别表示画布的行数、列数和当前图像的位置。在这个例子中,我们将画布分成了两行一列,第一个图像在第一行,第二个图像在第二行。因此,第一个图像的位置是(1, 1),第二个图像的位置是(2, 1)。
相关问题
用matplotlib显示三张图片
在Python中,你可以使用matplotlib库来创建图像,并通过其subplot函数方便地显示多张图片。以下是一个简单的示例,展示如何在同一幅图上显示三张图片:
```python
import matplotlib.pyplot as plt
from PIL import Image
# 假设你有三个图片文件路径,如 'image1.jpg', 'image2.jpg', 'image3.jpg'
img1 = Image.open('image1.jpg')
img2 = Image.open('image2.jpg')
img3 = Image.open('image3.jpg')
# 创建一个新的3x1网格
fig, axs = plt.subplots(3, 1)
# 显示每张图片
axs[0].imshow(img1)
axs[0].axis('off') # 关闭坐标轴,让图片更整洁
axs[1].imshow(img2)
axs[1].axis('off')
axs[2].imshow(img3)
axs[2].axis('off')
# 显示图像
plt.show()
用matplotlib显示4张图片
在Python中,你可以使用matplotlib库来创建图表,包括显示图片。如果你想同时展示四张图片,可以使用`plt.subplots()`函数创建一个包含四个子图的小窗口。以下是一个简单的例子:
```python
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# 假设你有四张图片文件名为image1.png, image2.png, image3.png, image4.png
images = [mpimg.imread(img_path) for img_path in ['image1.png', 'image2.png', 'image3.png', 'image4.png']]
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10, 10)) # 创建一个2x2的网格
for i, ax in enumerate(axs.flat):
ax.imshow(images[i]) # 在每个子图上显示一张图片
ax.set_title(f"Image {i+1}") # 添加标题
ax.axis('off') # 关闭坐标轴
plt.tight_layout() # 使子图之间的间距合适
plt.show()
```
阅读全文
相关推荐












