网站首页 > 教程文章 正文
一、简介
Matplotlib 是 Python 中最流行的数据可视化库,提供从简单折线图到复杂3D图形的完整解决方案。其核心优势在于:
o 灵活性强:支持像素级样式控制
o 兼容性好:与 NumPy、Pandas 无缝协作
o 扩展性强:支持 LaTeX 公式、动画等高级功能
二、安装与导入
pip install matplotlib
导入方式与Jupyter设置:
import matplotlib.pyplot as plt # 标准导入方式
import numpy as np # 用于生成示例数据
%matplotlib inline # 在Jupyter中内嵌显示图表
三、核心概念:Figure与Axes
# Figure相当于画布,Axes是绘图区域
fig = plt.figure(figsize=(8, 6)) # 创建8x6英寸的画布
ax = fig.add_subplot(1,1,1) # 添加一个1x1的绘图区域
ax.plot([1,2,3], [4,5,1]) # 在Axes上绘图
plt.show()
四、两种绘图模式对比
1. pyplot快捷模式(适合简单图表)
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.title('Quick Plot Demo')
plt.legend()
plt.show()
2. 面向对象模式(适合复杂图表)
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(x, np.cos(x), color='red', linestyle='--', label='cos(x)')
ax.set_title('OOP Style Demo')
ax.legend()
plt.show()
五、常见图表类型
1. 折线图(趋势分析)
# 对比两条产品线季度销售额
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
product_A = [230, 450, 300, 700]
product_B = [180, 400, 350, 650]
fig, ax = plt.subplots()
ax.plot(quarters, product_A, marker='o', label='Product A')
ax.plot(quarters, product_B, marker='s', label='Product B')
ax.set_title('Quarterly Sales Trend')
ax.set_xlabel('Quarter')
ax.set_ylabel('Sales (Million $)')
ax.grid(alpha=0.3)
ax.legend()
plt.show()
2. 柱状图(类别对比)
# 不同编程语言使用率对比
languages = ['Python', 'Java', 'C++', 'JavaScript']
popularity = [75, 60, 45, 55]
fig, ax = plt.subplots()
bars = ax.bar(languages, popularity, color=['#2ca02c', '#d62728', '#1f77b4', '#9467bd'])
ax.set_title('Programming Language Popularity')
ax.set_ylabel('Usage (%)')
# 为每个柱子添加数值标签
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height,
f'{height}%',
ha='center', va='bottom')
plt.show()
3. 散点图(相关性分析)
# 汽车价格与马力的关系
np.random.seed(42)
price = np.random.normal(35000, 15000, 100)
horsepower = 0.8 * price + np.random.normal(0, 5000, 100)
fig, ax = plt.subplots()
scatter = ax.scatter(price, horsepower, c=horsepower, cmap='viridis', alpha=0.7)
ax.set_title('Car Price vs Horsepower')
ax.set_xlabel('Price ($)')
ax.set_ylabel('Horsepower')
fig.colorbar(scatter, label='Horsepower') # 添加颜色条
plt.show()
4. 直方图(分布分析)
# 学生考试成绩分布
scores = np.random.normal(75, 10, 200)
fig, ax = plt.subplots()
ax.hist(scores, bins=20, edgecolor='black', alpha=0.7)
ax.set_title('Exam Score Distribution')
ax.set_xlabel('Score')
ax.set_ylabel('Frequency')
ax.axvline(scores.mean(), color='red', linestyle='--', label='Mean') # 添加均值线
ax.legend()
plt.show()
六、高级样式控制
1. 全局样式设置
plt.style.use('ggplot') # 应用杂志风格
print(plt.style.available) # 查看所有内置样式
2. 坐标轴高级设置
fig, ax = plt.subplots()
ax.plot(x, np.tan(x))
# 设置坐标轴范围与刻度
ax.set_xlim(0, 10)
ax.set_ylim(-5, 5)
ax.set_xticks(np.arange(0, 11, 2)) # 每2个单位一个刻度
ax.set_xticklabels(['Start', '2', '4', '6', '8', 'End']) # 自定义标签
# 添加参考线
ax.axhline(0, color='black', linewidth=0.8) # x轴参考线
3. 双坐标轴示例
# 温度与降水量双轴图表
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
temp = [5, 7, 11, 16, 21]
rainfall = [80, 60, 45, 30, 20]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(months, temp, 'r-', marker='o', label='Temperature')
ax2.bar(months, rainfall, alpha=0.3, label='Rainfall')
ax1.set_ylabel('Temperature (°C)', color='red')
ax2.set_ylabel('Rainfall (mm)', color='blue')
fig.legend(loc='upper left')
plt.show()
七、子图与布局
1. 网格布局
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# 左上:折线图
axs[0,0].plot(x, np.sin(x), color='blue')
axs[0,0].set_title('Sine Wave')
# 右上:柱状图
axs[0,1].bar(['A', 'B', 'C'], [25, 40, 30], color='orange')
# 左下:散点图
axs[1,0].scatter(np.random.rand(50), np.random.rand(50), c='green')
# 右下:饼图
axs[1,1].pie([30, 70], labels=['Yes', 'No'], autopct='%1.1f%%')
plt.tight_layout() # 自动调整间距
plt.show()
2. 自定义复杂布局
fig = plt.figure(figsize=(12, 6))
gs = fig.add_gridspec(2, 2) # 创建2x2网格
ax_main = fig.add_subplot(gs[:, 0]) # 左列合并
ax_right = fig.add_subplot(gs[0, 1]) # 右上
ax_bottom = fig.add_subplot(gs[1, 1]) # 右下
ax_main.plot(x, np.sin(x))
ax_right.pie([20, 80], labels=['A', 'B'])
ax_bottom.scatter(x, np.cos(x))
plt.show()
八、实战技巧
1. 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows系统
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示异常
2. 结合Pandas使用
import pandas as pd
df = pd.read_csv('sales_data.csv')
fig, ax = plt.subplots()
ax.plot(df['date'], df['revenue'], label='营收')
ax.plot(df['date'], df['cost'], label='成本')
ax.set_title('公司月度财务趋势')
ax.legend()
plt.show()
3. 保存高质量图片
plt.savefig('analysis_report.png',
dpi=300, # 高分辨率
bbox_inches='tight', # 去除白边
transparent=True, # 透明背景
facecolor='white' # 画布颜色
)
九、学习建议
- 官方资源:
- 文档:matplotlib.org
- 示例库:plt.gallery() 查看所有示例
- 调试技巧:
print(ax.get_children()) # 查看所有图表元素
- 进阶路线:
- 学习Seaborn库简化统计图表
- 探索mplot3d绘制3D图形
- 使用Plotly制作交互式图表
猜你喜欢
- 2025-04-05 python3 matplotlib下增加新字体并使用
- 2025-04-05 matplotlib 笔记2:调整边界、多个子图、inset子图
- 2025-04-05 Matplotlib直方图(matplotlib直方图高度)
- 2025-04-05 Matplotlib饼状图(matplotlib 饼状图)
- 2025-04-05 一图入门matplotlib(matplotlib绘图基础)
- 2025-04-05 【Python】一文学会使用 Matplotlib 库(数据可视化)
- 2025-04-05 Matplotlib Figures的创建、显示和保存
- 2025-04-05 Python技巧之使用Matplotlib绘制数据图表
- 2025-04-05 为什么你觉得Matplotlib用起来困难?因为你还没看过这个思维导图
- 2025-04-05 基于matplotlib轻松绘制漂亮的表格
- 最近发表
-
- 网络安全干货知识 | 手把手搭建 k8s docker 漏洞环境
- docker+k8s 报错(k8s docker login)
- K8s 集群运行时:从 Docker 升级到 Containerd
- 轻松掌握k8s安装(使用docker)知识点
- 什么是 k8s(Kubernetes)?Docker 与 Kubernetes选择哪一个?
- 从 Docker 到 K8s:初学者常见的误区盘点
- Docker容器是什么?K8s和它有什么关系呢?
- Docker 是什么? 它与K8S之间是什么关系?
- Docker是什么?K8s是什么?如何从0到1实现Docker与K8s全流程部署
- K8S与Docker的区别(k8s与docker的区别是啥)
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- mybatis plus page (35)
- vue @scroll (38)
- 堆栈区别 (33)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)
- redis aof rdb 区别 (33)
- 302跳转 (33)
- http method (35)
- js array splice (33)