1. Matplotlib绘图基础与核心概念
Matplotlib是Python生态中最经典的数据可视化库,由John Hunter于2003年创建。作为科学计算领域的事实标准,它提供了类似MATLAB的绘图接口,同时完美支持Numpy数组操作。我在金融数据分析工作中使用Matplotlib已有7年,处理过从简单折线图到复杂3D建模的各种场景。
核心架构分为三层:
- Backend层:处理与操作系统图形界面的底层交互(如Agg、GTK、Qt等)
- Artist层:负责图形元素的绘制和样式控制(Figure、Axes、Line2D等对象)
- Scripting层:面向用户的pyplot模块,提供快速绘图API
安装只需一行命令:
bash复制pip install matplotlib
重要提示:在Jupyter Notebook中使用时,需添加
%matplotlib inline魔法命令才能显示图形。如果是交互式开发,推荐使用%matplotlib notebook获得缩放平移等交互功能。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 基础图形绘制实战
2.1 折线图绘制与样式控制
折线图是展示时间序列数据的首选。以下示例展示如何绘制带自定义样式的正弦曲线:
python复制import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.figure(figsize=(10, 5)) # 设置画布尺寸
plt.plot(x, y,
color='#FF6B6B', # 十六进制颜色
linewidth=3, # 线宽
linestyle='--', # 虚线样式
marker='o', # 数据点标记
markersize=8, # 标记尺寸
label='sin(x)') # 图例标签
plt.title("正弦函数曲线", fontsize=14, pad=20) # pad调整标题间距
plt.xlabel("X轴", fontsize=12)
plt.ylabel("Y轴", fontsize=12)
plt.grid(alpha=0.3) # 网格线透明度
plt.legend(loc='upper right') # 图例位置
plt.tight_layout() # 自动调整子图间距
plt.show()
样式控制要点:
- 颜色支持多种格式:颜色名称('red')、十六进制值('#FF6B6B')、RGB元组((1,0,0))
- 线型常用选项:'-'实线、'--'虚线、':'点线、'-.'点划线
- 标记样式:'o'圆形、's'方形、'^'三角形等20余种
2.2 柱状图与分组展示
比较不同类别数据时,柱状图比折线图更直观。下面是分组柱状图的实现方法:
python复制labels = ['2020', '2021', '2022']
sales_A = [23, 45, 37]
sales_B = [34, 30, 41]
x = np.arange(len(labels)) # 生成位置索引
width = 0.35 # 柱宽
fig, ax = plt.subplots(figsize=(8,6))
rects1 = ax.bar(x - width/2, sales_A, width, label='产品A',
color='#4ECDC4', edgecolor='black', linewidth=1)
rects2 = ax.bar(x + width/2, sales_B, width, label='产品B',
color='#FF6B6B', edgecolor='black', linewidth=1)
# 添加数据标签
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.annotate(f'{height}',
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 垂直偏移
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylabel('销售额(万元)')
ax.set_title('年度产品销售额对比')
ax.legend()
fig.tight_layout()
分组柱状图技巧:
- 使用
np.arange生成位置索引,通过±width/2实现分组偏移 edgecolor和linewidth参数为柱体添加描边更美观annotate方法添加数据标签时,注意xytext的偏移量单位是points
3. 高级可视化技巧
3.1 多子图与组合图形
使用plt.subplots()可以创建复杂的多子图布局。下面的例子展示2x2网格中包含四种不同类型的图形:
python复制fig, axs = plt.subplots(2, 2, figsize=(12, 10))
# 子图1:散点图
x = np.random.randn(100)
y = x + np.random.randn(100)*0.5
axs[0,0].scatter(x, y, alpha=0.6, c=np.arctan2(y, x), cmap='hsv')
axs[0,0].set_title('彩色散点图')
# 子图2:饼图
sizes = [15, 30, 45, 10]
labels = ['A组', 'B组', 'C组', 'D组']
explode = (0, 0.1, 0, 0) # 突出第二块
axs[0,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
axs[0,1].axis('equal') # 保证饼图是圆形
axs[0,1].set_title('占比分析')
# 子图3:直方图
mu, sigma = 100, 15
data = mu + sigma * np.random.randn(1000)
axs[1,0].hist(data, bins=30, density=True, alpha=0.6, color='g')
axs[1,0].set_title('正态分布直方图')
# 子图4:箱线图
np.random.seed(10)
data = [np.random.normal(0, std, 100) for std in range(1,4)]
axs[1,1].boxplot(data, vert=True, patch_artist=True,
labels=['组1', '组2', '组3'])
axs[1,1].set_title('分组箱线图')
fig.suptitle('多类型图形组合展示', y=1.02, fontsize=16)
plt.tight_layout()
子图布局经验:
figsize参数应根据子图数量合理设置,避免图形挤压tight_layout()自动调整间距,也可手动指定subplots_adjust参数- 共享坐标轴可通过
sharex/sharey参数实现
3.2 3D图形绘制
Matplotlib支持基本的3D可视化,需要先导入mplot3d工具包:
python复制from mpl_toolkits import mplot3d
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
# 生成数据
theta = np.linspace(0, 2*np.pi, 100)
z = np.linspace(0, 10, 100)
r = z**2 + 1
x = r * np.sin(theta)
y =
