matplotlab子图
时间: 2025-03-22 18:14:33 浏览: 25
### Matplotlib 中创建和操作子图
#### 使用 `subplot()` 方法
`subplot()` 是一种简单且常用的方式来创建子图。该函数会自动管理布局并返回一个轴对象,可以通过传递行数、列数以及当前子图的位置来定义子图。
以下是使用 `subplot()` 的示例代码:
```python
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
# 创建第一个子图
plt.subplot(2, 2, 1) # 参数表示 (rows, columns, index)
plt.plot([0, 1], [0, 1])
plt.title('Subplot 1')
# 创建第二个子图
plt.subplot(2, 2, 2)
plt.scatter([0, 1], [1, 0])
plt.title('Subplot 2')
# 创建第三个子图
plt.subplot(2, 2, 3)
plt.bar(['A', 'B'], [3, 5])
plt.title('Subplot 3')
# 创建第四个子图
plt.subplot(2, 2, 4)
plt.hist([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], bins=5)
plt.title('Subplot 4')
plt.tight_layout()
plt.show()
```
---
#### 使用 `subplots()` 方法
`subplots()` 提供了一种更灵活的方式一次性创建多个子图,并返回一个包含所有轴对象的数组。这种方法特别适合于需要统一调整共享属性的情况。
以下是一个例子:
```python
fig, axs = plt.subplots(2, 2, figsize=(8, 6)) # 返回 fig 和 ax 数组
axs[0, 0].plot([0, 1], [0, 1]) # 访问特定子图
axs[0, 0].set_title('Subplot 1')
axs[0, 1].scatter([0, 1], [1, 0])
axs[0, 1].set_title('Subplot 2')
axs[1, 0].bar(['A', 'B'], [3, 5])
axs[1, 0].set_title('Subplot 3')
axs[1, 1].hist([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], bins=5)
axs[1, 1].set_title('Subplot 4')
plt.tight_layout()
plt.show()
```
---
#### 使用 `add_subplot()` 方法
`add_subplot()` 可以手动向 Figure 对象添加单个子图。此方法提供了更大的灵活性,尤其是在复杂布局的情况下。
下面展示了一个简单的例子:
```python
fig = plt.figure(figsize=(8, 6))
# 添加第一个子图
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot([0, 1], [0, 1])
ax1.set_title('Add Subplot 1')
# 添加第二个子图
ax2 = fig.add_subplot(2, 2, 2)
ax2.scatter([0, 1], [1, 0])
ax2.set_title('Add Subplot 2')
# 添加第三个子图
ax3 = fig.add_subplot(2, 2, 3)
ax3.bar(['A', 'B'], [3, 5])
ax3.set_title('Add Subplot 3')
# 添加第四个子图
ax4 = fig.add_subplot(2, 2, 4)
ax4.hist([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], bins=5)
ax4.set_title('Add Subplot 4')
plt.tight_layout()
plt.show()
```
---
#### 结合 Pandas 数据框绘图
如果正在处理的是 Pandas DataFrame,则可以直接调用其内置的 `.plot()` 方法来快速生成图表。这种方式通常不需要显式地创建子图,但仍可通过设置参数实现自定义效果。
例如:
```python
import pandas as pd
data = {'Category': ['A', 'B', 'C'],
'Value1': [1, 2, 3],
'Value2': [4, 5, 6]}
df = pd.DataFrame(data)
fig, ax = plt.subplots()
df.plot(kind='bar', x='Category', y=['Value1', 'Value2'], ax=ax)
ax.set_title('Pandas Plot Example')
plt.show()
```
上述方法展示了如何通过不同方式在 Matplotlib 中创建和操作子图[^3]。
---
阅读全文
相关推荐

















