Python Matplotlib数据可视化实战指南

Python Matplotlib数据可视化实战

一、Matplotlib简介

Matplotlib是Python最流行的2D绘图库,可以绘制折线图、柱状图、散点图、饼图、热力图等各种图表。

二、环境配置

python 复制代码
pip install matplotlib seaborn
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

三、基本绑图流程

python 复制代码
fig, ax = plt.subplots(figsize=(10, 6))
x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y, label='sin(x)', color='#2E86AB', linewidth=2)
ax.set_xlabel('X轴', fontsize=12)
ax.set_ylabel('Y轴', fontsize=12)
ax.set_title('正弦函数曲线', fontsize=14, fontweight='bold')
ax.legend()
plt.tight_layout()
plt.savefig('sin_curve.png', dpi=150)
plt.show()

四、常见图表类型

1. 柱状图

python 复制代码
fig, ax = plt.subplots(figsize=(10, 6))
languages = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
popularity = [30.5, 17.2, 8.9, 7.3, 6.5]
colors = ['#3498db', '#e74c3c', '#f39c12', '#27ae60', '#9b59b6']
bars = ax.bar(languages, popularity, color=colors)
for bar, val in zip(bars, popularity):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, f'{val}%', ha='center')
plt.tight_layout()
plt.savefig('bar_chart.png', dpi=150)
plt.show()

2. 散点图

python 复制代码
fig, ax = plt.subplots(figsize=(10, 6))
np.random.seed(42)
x = np.random.randn(100) * 50 + 170
y = np.random.randn(100) * 15 + 65
scatter = ax.scatter(x, y, c=y, cmap='viridis', alpha=0.7, s=80)
plt.colorbar(scatter, label='体重 (kg)')
ax.set_xlabel('身高 (cm)')
ax.set_ylabel('体重 (kg)')
plt.tight_layout()
plt.savefig('scatter_plot.png', dpi=150)
plt.show()

3. 饼图

python 复制代码
fig, ax = plt.subplots(figsize=(10, 8))
categories = ['销售部', '技术部', '市场部', '人事部', '财务部']
budgets = [350000, 280000, 180000, 80000, 110000]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
wedges, texts, autotexts = ax.pie(budgets, labels=categories, colors=colors, autopct='%1.1f%%', shadow=True)
plt.tight_layout()
plt.savefig('pie_chart.png', dpi=150)
plt.show()

4. 热力图

python 复制代码
import seaborn as sns
fig, ax = plt.subplots(figsize=(10, 8))
np.random.seed(42)
data = np.random.rand(8, 8)
sns.heatmap(data, annot=True, fmt='.2f', cmap='YlOrRd', ax=ax)
plt.tight_layout()
plt.savefig('heatmap.png', dpi=150)
plt.show()

五、多子图布局

python 复制代码
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
x = np.arange(12)
y1 = np.random.randint(50, 100, 12)
axes[0, 0].plot(x, y1, marker='o', color='#3498db')
axes[0, 1].bar(['A', 'B', 'C', 'D'], [75, 90, 60, 85])
axes[1, 0].pie([25, 35, 20, 20], labels=['甲', '乙', '丙', '丁'], autopct='%1.1f%%')
axes[1, 1].hist(np.random.randn(1000), bins=30, color='#9b59b6', alpha=0.7)
plt.suptitle('数据分析仪表盘', fontsize=16, fontweight='bold')
plt.tight_layout()
plt.savefig('dashboard.png', dpi=150)
plt.show()

六、实验结果

不同图表类型适用场景:

图表类型 适用场景 特点
折线图 趋势变化 清晰展示时间序列变化
柱状图 对比分析 直观比较不同类别数值
散点图 相关分析 发现变量间关系
饼图 占比展示 显示部分与整体比例
热力图 矩阵数据 展示二维数据的数值分布

七、总结

Matplotlib是Python可视化的基础库,通过合理选择图表类型和精心设计样式,可以制作出专业的数据分析报告。


标签: Python | Matplotlib | Seaborn | 数据可视化 | 图表

相关推荐
代码山河5 小时前
Python就业方向全解析:后端、爬虫、数据分析、AI你选哪个?
python·学习·架构·教程·面向对象·项目
在世修行5 小时前
智学文枢:题目流水线
python·多线程·状态机·pyside
梯度下降者5 小时前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
“AI国潮设计-小江”7 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
benchmark_cc8 小时前
用 Python 拉 A 股全市场实时快照:Notebook 请求、结果校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
伞伞悦读8 小时前
【第70期】Adam二阶矩不是方差:偏差校正、动量与AdamW完整实验
python
外收内放9 小时前
Python基础语法练习题(73)
java·前端·python
锋行天下9 小时前
Langgraph HITL 中断运行,用户输入后输出打字效果
人工智能·python
时早玖沐9 小时前
给 AstrBot 写一个天气推送插件:12 次提交、6 个坑
python·开源·ai编程
触底反弹9 小时前
🚀 FastAPI 五大重难点深度剖析:从 500 报错到彻底搞懂 Depends、Pydantic 与 SQLAlchemy
python·fastapi