Matplotlib绘图同时多张figure
时间: 2023-12-04 07:05:44 浏览: 31
要同时绘制多张图,可以使用Matplotlib中的子图(subplot)功能,或者使用面向对象编程的方式创建多个Figure对象。下面分别给出两种方法的示例代码:
使用subplot方法:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
# 创建子图
fig, axs = plt.subplots(3, 1, figsize=(6, 8), sharex=True)
# 绘制图像
axs[0].plot(x, y1)
axs[0].set_title('Sin(x)')
axs[1].plot(x, y2)
axs[1].set_title('Cos(x)')
axs[2].plot(x, y3)
axs[2].set_title('Tan(x)')
# 设置整体标题
fig.suptitle('Trigonometric Functions')
# 显示图像
plt.show()
```
上述代码中,通过`plt.subplots`创建一个3行1列的子图,返回的fig对象是整个图像的容器,axs是每个子图的Axes对象,可以通过索引访问。
使用面向对象编程的方式:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
# 创建Figure对象
fig1 = plt.figure(figsize=(6, 4))
ax1 = fig1.add_subplot(111)
ax1.plot(x, y1)
ax1.set_title('Sin(x)')
fig2 = plt.figure(figsize=(6, 4))
ax2 = fig2.add_subplot(111)
ax2.plot(x, y2)
ax2.set_title('Cos(x)')
fig3 = plt.figure(figsize=(6, 4))
ax3 = fig3.add_subplot(111)
ax3.plot(x, y3)
ax3.set_title('Tan(x)')
# 显示图像
plt.show()
```
上述代码中,通过`plt.figure`分别创建3个Figure对象,`fig.add_subplot(111)`返回的是Axes对象,可以在上面绘制图像。需要注意的是,每个Figure对象是独立的,可以设置不同的大小、背景色等属性。