### 使用 `matplotlib.pyplot` 绘图的基础方法
#### 基本绘图功能
`matplotlib.pyplot` 是 Python 中常用的可视化工具之一,提供了丰富的接口来创建各种类型的图表。以下是几个常见的绘图方法及其用法:
1. **基本折线图**
折线图是最基础的图形形式,可以通过 `plt.plot()` 函数实现。
```python
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y, label='y=x^2', color='blue') # 设置颜色和标签
plt.title('Basic Line Plot')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.legend()
plt.show()
```
2. **自定义坐标轴范围**
可以通过 `plt.axis()` 来调整图像显示的坐标轴范围[^1]。
```python
plt.plot(x, y, label='y=x^2', color='green')
plt.axis([0, 5, 0, 20]) # 调整x轴范围为[0, 5], y轴范围为[0, 20]
plt.legend()
plt.show()
```
3. **设置刻度标记**
刻度的位置和标签可以通过 `plt.xticks()` 和 `plt.yticks()` 自定义[^2]。
```python
plt.plot(x, y, label='y=x^2', color='red')
plt.xticks([0, 1, 2, 3, 4], ['A', 'B', 'C', 'D', 'E']) # 替换默认刻度名称
plt.yticks([0, 5, 10, 15, 20])
plt.legend()
plt.show()
```
4. **添加注解**
图形上的特定点可以用 `plt.annotate()` 添加文字说明[^3]。
```python
plt.plot(x, y, label='y=x^2', color='purple')
plt.annotate('Max Point',
xy=(4, 16),
xytext=(3, 8),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.legend()
plt.show()
```
5. **多条曲线对比**
同一张图上可以绘制多个数据序列并加以区分。
```python
x = [0, 1, 2, 3, 4]
y1 = [i**2 for i in x]
y2 = [i*2 for i in x]
plt.plot(x, y1, linestyle='-', marker='o', label='Quadratic')
plt.plot(x, y2, linestyle='--', marker='s', label='Linear') # 不同样式表示不同关系
plt.legend()
plt.show()
```
---
### 高级绘图技巧
除了上述基本操作外,还可以利用更复杂的选项来自定义图表。
1. **子图布局**
多个独立的小图可以在同一窗口中展示,使用 `plt.subplots()` 实现[^4]。
```python
fig, axs = plt.subplots(2)
axs[0].plot(x, y1, label='y=x^2')
axs[0].set_title('Subplot 1')
axs[0].legend()
axs[1].plot(x, y2, label='y=2*x')
axs[1].set_title('Subplot 2')
axs[1].legend()
plt.tight_layout() # 自动调整间距
plt.show()
```
2. **保存图片**
将生成的图表保存到本地文件中。
```python
plt.savefig('my_plot.png', dpi=300) # 指定分辨率
```
---