### 使用 Matplotlib.pyplot 绘制图形
Matplotlib 是 Python 中广泛使用的数据可视化库,其中 `pyplot` 模块提供了类似于 MATLAB 的绘图接口。通过该模块可以轻松创建各种类型的图表。
#### 创建简单的折线图
为了展示基本的绘图功能,下面是一个简单例子来绘制一条折线:
```python
import matplotlib.pyplot as plt
# 数据准备
x_values = [0, 1, 2, 3, 4]
y_values = [0, 2, 1, 3, 4]
plt.plot(x_values, y_values) # 调用 plot 方法绘制线条
plt.xlabel('X Axis') # 设置 X 轴标签
plt.ylabel('Y Axis') # 设置 Y 轴标签
plt.title('Simple Line Plot') # 添加标题
plt.grid(True) # 显示网格
plt.show() # 展示图像窗口
```
这段代码会生成一张带有坐标轴标记、标题以及背景网格的基础折线图[^1]。
#### 自定义样式与属性
除了默认设置外,还可以自定义颜色、宽度和其他视觉效果:
```python
plt.figure(figsize=(8, 6)) # 设定画布大小
plt.plot(
x_values,
y_values,
color='red', # 线条颜色
linewidth=2.5, # 线宽
linestyle='--' # 线型 (虚线)
)
for i in range(len(x_values)):
plt.text(x_values[i], # 文本位置横坐标
y_values[i]+0.2, # 文本位置纵坐标偏移量
f'{i}', # 所要显示的内容
ha='center',
va='bottom'
)
plt.xlim(-1, max(x_values)+1)# 设置 x 范围
plt.ylim(min(y_values)-1,max(y_values)+2)# 设置 y 范围
plt.xticks(range(0, int(max(x_values))+2))
plt.yticks([min(y_values),max(y_values)])
plt.legend(['Line'], loc="upper left") # 图例说明
plt.tight_layout()
plt.savefig('line_plot.png')
plt.close()
```
此部分展示了更多关于调整图表外观的方法,包括但不限于改变线条的颜色、粗细和风格;添加文字标注;控制刻度范围等操作。
#### 子图布局管理
当需要在同一张图片内放置多个独立的小图时,则需要用到 subplot 或者 subplots 函数来进行多面板布置:
```python
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(9, 6))
axs[0][0].plot(x_values, y_values,'g*-')
axs[0][0].set_title('Subplot 1')
axs[0][1].scatter(x_values,y_values,c='blue')
axs[0][1].set_title('Scatter Subplot')
axs[1][0].bar(x_values, y_values,color='orange')
axs[1][0].set_title('Bar Chart')
axs[1][1].stackplot(x_values,[y_values]*len(x_values))
axs[1][1].set_title('Stacked Area')
plt.suptitle('Multiple Plots Example')
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()
```
上述脚本实现了四个不同种类的小图排列在一个大框架之中,并各自赋予了相应的标题[^2].
#### 特殊类型图表 - 堆积面积图
堆积面积图是一种特殊形式的时间序列分析工具,在金融领域应用较为普遍。这里给出一个具体的实现方式:
```python
import numpy as np
labels = ['G1','G2','G3']
data = [[1,2,3],[4,5,6],[7,8,9]]
width = 0.5
fig, ax = plt.subplots()
cumulative_data=np.cumsum(data,axis=0).tolist()[::-1]
colors=['tab:red','tab:blue','tab:green']
for idx,(row,col)in enumerate(zip(cumulative_data[::-1],data)):
bottom=None if idx==0 else cumulative_data[idx-1]
ax.bar(labels,row,bottom=bottom,label=f'Series {idx+1}',color=colors[idx])
ax.set_ylabel('Values')
ax.set_title('Stacked Bar with Multiple Series')
ax.legend(loc='best')
plt.show()
```
这个案例中还涉及到了 NumPy 库用于处理矩阵运算,从而更方便地构建累积数据结构以便于后续作图需求[^3].