知识知多少——Matplotlib 库
文章目录
- Matplotlib 库详解(新版)
- 一、Matplotlib 核心概念
- 1. 基本架构
- 2. 两种编程接口
- 二、新版 Matplotlib 安装与配置
- 安装
- 配置中文显示(新版推荐方式)
- 三、基本绘图示例
- 1. 折线图
- 2. 柱状图(新版样式)
- 四、新版特性与改进
- 1. 样式系统改进
- 2. 新的颜色周期系统
- 3. 改进的 3D 绘图
- 五、高级功能
- 1. 多子图布局
- 2. 动画功能
- 六、图像保存优化
- 七、常见问题解决
Matplotlib 库详解(新版)
Matplotlib 是 Python 最著名的 2D 绘图库,提供了一套完整的绘图 API,可以生成出版质量级别的图形。以下是针对新版 Matplotlib (≥3.6) 的详细介绍和使用方法。
一、Matplotlib 核心概念
1. 基本架构
- FigureCanvas:绘图区域(画布)
- Figure:图形容器(可以包含多个 Axes)
- Axes:坐标系(实际绘图区域)
- Artist:所有可见元素(线条、文本、图像等)
2. 两种编程接口
- pyplot 接口:MATLAB 风格,适合快速绘图
- 面向对象接口:更灵活,适合复杂图形
二、新版 Matplotlib 安装与配置
安装
pip install --upgrade matplotlib
配置中文显示(新版推荐方式)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei'] # 设置中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
三、基本绘图示例
1. 折线图
import numpy as npx = np.linspace(0, 10, 100)
y = np.sin(x)fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y, label='正弦曲线', color='blue', linewidth=2)
ax.set_title('正弦函数曲线', fontsize=14)
ax.set_xlabel('X轴', fontsize=12)
ax.set_ylabel('Y轴', fontsize=12)
ax.legend()
ax.grid(True, linestyle='--', alpha=0.6)
plt.tight_layout()
plt.show()
2. 柱状图(新版样式)
labels = ['苹果', '香蕉', '橙子']
values = [45, 30, 25]fig, ax = plt.subplots(figsize=(6, 4))
bars = ax.bar(labels, values, color=['#1f77b4', '#ff7f0e', '#2ca02c'])# 添加数据标签
for bar in bars:height = bar.get_height()ax.text(bar.get_x() + bar.get_width()/2., height,f'{height}%',ha='center', va='bottom')ax.set_title('水果偏好调查', pad=20)
ax.set_ylabel('百分比(%)')
plt.show()
四、新版特性与改进
1. 样式系统改进
新版推荐使用 seaborn-v0_8
替代旧的 seaborn
样式:
plt.style.use('seaborn-v0_8') # 新版推荐
# 或使用白色网格背景
plt.style.use('seaborn-v0_8-whitegrid')
2. 新的颜色周期系统
# 获取默认颜色循环
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
print(colors) # 新版默认10色循环
3. 改进的 3D 绘图
from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))surf = ax.plot_surface(X, Y, Z, cmap='viridis')
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_title('3D 曲面图')
plt.show()
五、高级功能
1. 多子图布局
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
fig.suptitle('多子图示例', y=1.02)# 子图1
axs[0, 0].plot(x, np.sin(x), 'r-')
axs[0, 0].set_title('正弦函数')# 子图2
axs[0, 1].plot(x, np.cos(x), 'b--')
axs[0, 1].set_title('余弦函数')# 子图3
axs[1, 0].scatter(np.random.rand(50), np.random.rand(50), c='g')
axs[1, 0].set_title('散点图')# 子图4
axs[1, 1].hist(np.random.randn(1000), bins=30, color='purple')
axs[1, 1].set_title('直方图')plt.tight_layout()
plt.show()
2. 动画功能
from matplotlib.animation import FuncAnimationfig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
line, = ax.plot(x, np.sin(x))def update(frame):line.set_ydata(np.sin(x + frame/10))return line,ani = FuncAnimation(fig, update, frames=100, interval=50)
plt.show()
六、图像保存优化
新版推荐保存方法:
fig.savefig('output.png', dpi=300, bbox_inches='tight', facecolor='white', edgecolor='none',quality=95)
七、常见问题解决
-
中文显示问题:
- 确保系统中安装了相应中文字体
- 或使用绝对字体路径:
plt.rcParams['font.sans-serif'] = ['/path/to/your/font.ttf']
-
性能优化:
- 大数据集使用
rasterized=True
- 关闭交互模式:
plt.ioff()
- 大数据集使用
-
新版弃用警告:
- 使用
seaborn-v0_8
替代seaborn
- 使用
subplots()
替代subplot()
- 使用
Matplotlib 功能强大且灵活,以上只是基础介绍。建议查阅官方文档获取最新信息和更高级用法。