fig,ax= plt.subplots()
时间: 2025-07-13 13:18:49 浏览: 7
在使用 `matplotlib` 的 `subplots()` 方法创建多个子图后,可以通过调用 `fig.savefig()` 来保存整个图形为图片文件。以下是具体的代码示例:
```python
import matplotlib.pyplot as plt
# 创建一个 2x2 子图布局
fig, axs = plt.subplots(2, 2)
# 设置每个子图的内容
axs[0, 0].plot([1, 2, 3], [4, 5, 6])
axs[0, 0].set_title('Subplot 1')
axs[0, 1].scatter([1, 2, 3], [4, 5, 6])
axs[0, 1].set_title('Subplot 2')
axs[1, 0].bar([1, 2, 3], [4, 5, 6])
axs[1, 0].set_title('Subplot 3')
axs[1, 1].hist([1, 2, 3, 4, 5, 6, 7, 8, 9])
axs[1, 1].set_title('Subplot 4')
# 调整子图之间的间距以防止重叠
plt.tight_layout()
# 保存整个 figure 到文件
fig.savefig('multi_subplots_figure.png', dpi=300, bbox_inches='tight') # 保存为 PNG 图片,分辨率 300 DPI
# 关闭图形窗口
plt.close(fig)
```
在这段代码中,`fig.savefig()` 是用于保存由 `plt.subplots()` 创建的整个图形的关键方法。它支持多种参数配置,例如指定输出文件名、分辨率 (`dpi`) 和边界框调整 (`bbox_inches`) 等[^1]。
---
### 注意事项
- 当使用 `plt.subplots()` 返回的对象时,`fig` 表示整个绘图对象,而 `axs` 是一个数组或矩阵形式的 Axes 对象集合,对应各个子图。
- 如果需要单独保存某个特定子图,则需对该子图对应的 `Axes` 进行操作,但这通常不推荐,因为会丢失整体布局信息。
- 参数 `bbox_inches='tight'` 可自动裁剪多余的空白区域,使保存的图片更加紧凑[^2]。
---
####
阅读全文
相关推荐

















