Matplotlib是Python最著名的绘图库,在科研、工程、金融等领域广泛应用。据2023年PyPI统计,Matplotlib月下载量超3500万次,是数据科学必备工具。
Matplotlib提供:
Matplotlib像数字画布:
模块 | 功能 | 常用类/函数 |
---|---|---|
pyplot | 快速绘图接口 | plot, scatter, bar |
axes | 精细控制绘图区域 | set_xlim, grid |
figure | 画布管理 | figsize, dpi |
animation | 动态可视化 | FuncAnimation |
mplot3d | 三维绘图 | Axes3D |
库 | 优点 | 缺点 |
---|---|---|
Matplotlib | 功能全面,定制性强 | API稍复杂 |
Seaborn | 统计图表美观 | 底层依赖Matplotlib |
Plotly | 交互性强 | 体积较大 |
pip install matplotlib numpy # 基础依赖
import matplotlib.pyplot as plt
import numpy as np
# 生成示例数据
x = np.arange(0, 10, 0.1) # 0-10之间每隔0.1取一个点
y = np.sin(x) # 正弦曲线模拟股价波动
# 创建画布和坐标系
plt.figure(figsize=(10, 5)) # 10英寸宽,5英寸高
# 绘制折线图
plt.plot(x, y,
color='blue',
linewidth=2,
linestyle='--',
label='Stock Trend')
# 添加图表元素
plt.title('Stock Price Simulation')
plt.xlabel('Trading Day')
plt.ylabel('Price ($)')
plt.legend() # 显示图例
plt.grid(True) # 显示网格
plt.show() # 显示图表
# 生成随机数据
np.random.seed(42)
heights = np.random.normal(170, 10, 100) # 均值170,标准差10
weights = heights * 0.6 + np.random.randn(100) * 15
# 创建散点图
plt.scatter(heights, weights,
c='green', # 点颜色
alpha=0.6, # 透明度
marker='o', # 点形状
s=50) # 点大小
# 添加回归线
m, b = np.polyfit(heights, weights, 1)
plt.plot(heights, m*heights + b, 'r--')
plt.title('Height vs Weight')
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.show()
products = ['A', 'B', 'C', 'D']
sales = [120, 85, 145, 65]
# 创建柱状图
bars = plt.bar(products, sales,
color=['#FF9999', '#66B2FF', '#99FF99', '#FFCC99'],
edgecolor='black')
# 添加数据标签
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height}',
ha='center', va='bottom')
plt.title('Quarterly Product Sales')
plt.ylabel('Units Sold')
plt.xticks(rotation=45)
plt.tight_layout() # 自动调整布局
plt.show()
案例1输出:显示正弦曲线图,包含标题、坐标轴、网格线
案例2输出:显示散点图+回归线,点呈绿色半透明
案例3输出:显示彩色柱状图,每个柱子顶部有数值标签
数据量 | 散点图耗时(ms) | 折线图耗时(ms) |
---|---|---|
1万 | 120 | 85 |
10万 | 350 | 210 |
100万 | 2800 | 1500 |
rasterized=True
样式预设:使用plt.style
plt.style.use('ggplot') # 专业商业风格
矢量图保存:PDF/SVG格式
plt.savefig('chart.pdf', dpi=300, bbox_inches='tight')
子图布局:使用GridSpec
gs = plt.GridSpec(2, 2) # 2行2列
颜色映射:用colormap
plt.scatter(x, y, c=z, cmap='viridis')
Latex支持:数学公式渲染
plt.title(r'$\alpha > \beta$')
未释放内存
plt.figure() # 创建后未关闭
混淆API层级
plt.plot() # pyplot API
ax.plot() # OO API混用
中文乱码
# 未设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
交互模式调试
plt.ion() # 开启交互模式
元素边界检查
print(ax.get_xlim()) # 查看坐标范围
工具 | 用途 |
---|---|
Seaborn | 统计图表美化 |
Pandas | 数据预处理 |
PyQt | 嵌入式GUI应用 |
终极挑战:使用Matplotlib复现《Nature》期刊中的科研图表
建议配合Jupyter Notebook实践:
%matplotlib inline # 在Notebook中直接显示图表