网站首页 > 文章精选 正文
一、简介
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-05-03 爬虫实战(二)爬取Ajax数据(爬取数据的代码)
- 2025-05-03 突破亚马逊壁垒,Web Unlocker API 助您轻松获取数据
- 2025-05-03 最实用的大数据可视化分析工具汇总
- 2025-05-03 专题|外行人看大数据 十款最常用的数据可视化工具
- 2025-05-03 网络爬虫——从网站中提取有用的数据
- 2025-05-03 这6款数据可视化软件,不会写代码也能用!
- 2025-05-03 B端技术常识:MVC模式(什么是mvc模式,各模块的作用是什么)
- 2025-05-03 越晚搞懂 MySQL JSON 数据类型,你就越吃亏
- 2025-05-03 JSON数据类型详细总结(json数据的数据值可以是哪些)
- 2025-05-03 基本数据类型你不知道的东西(基本数据类型一般由什么组成)
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 稳压管的稳压区是工作在什么区 (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)