Matplotlib完全指南:数据可视化从入门到实战
创作时间:
作者:
@小白创作中心
Matplotlib完全指南:数据可视化从入门到实战
引用
CSDN
1.
https://blog.csdn.net/qq_67342067/article/details/146375242
Matplotlib是Python最强大的数据可视化库,可以创建高质量的2D/3D图形,完美支持科学计算与数据分析。本文将深入讲解Matplotlib的核心功能,通过20+个实战案例,带你从基础绘图到高级可视化技巧,全面掌握数据图形化表达!
一、环境配置与基础概念
1.1 安装Matplotlib
pip install matplotlib
1.2 导入惯例
import matplotlib.pyplot as plt # 主要接口
import numpy as np # 配合使用
1.3 两种绘图模式
- 脚本模式:
plt.plot() + plt.show()
- 面向对象模式(推荐):
fig, ax = plt.subplots()
ax.plot(x, y)
二、基础图形绘制
2.1 折线图(Line Plot)
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(x, y,
color='red',
linestyle='--',
linewidth=2,
marker='o',
markersize=5,
label='sin(x)')
ax.set_title("正弦曲线示例")
ax.set_xlabel("X轴")
ax.set_ylabel("Y轴")
ax.legend()
plt.show()
2.2 柱状图(Bar Chart)
categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 45]
fig, ax = plt.subplots()
bars = ax.bar(categories, values,
color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'],
edgecolor='black')
# 添加数值标签
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_ylim(0, 50)
ax.grid(axis='y', linestyle='--')
三、高级图表类型
3.1 散点图(Scatter Plot)
x = np.random.randn(100)
y = x * 2 + np.random.randn(100)
fig, ax = plt.subplots()
scatter = ax.scatter(x, y,
c=np.abs(x+y), # 颜色映射
s=50, # 点大小
cmap='viridis',
alpha=0.7)
plt.colorbar(scatter, label='强度值')
3.2 饼图(Pie Chart)
labels = ['电子产品', '服饰', '食品', '图书']
sizes = [35, 25, 20, 20]
explode = (0.1, 0, 0, 0) # 突出显示第一项
fig, ax = plt.subplots()
ax.pie(sizes,
explode=explode,
labels=labels,
autopct='%1.1f%%',
shadow=True,
startangle=90)
ax.axis('equal') # 正圆形
3.3 直方图(Histogram)
data = np.random.normal(170, 10, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=30,
density=True, # 显示概率密度
histtype='stepfilled',
color='skyblue',
edgecolor='black')
ax.set_xlabel("Height distribution")
ax.set_ylabel("probability density")
四、多图布局与样式定制
4.1 子图布局(Subplots)
x = np.random.randn(100)
y = x * 2 + np.random.randn(100)
data = np.random.normal(170, 10, 1000)
labels = ['electronics', 'costume', 'food', 'book']
sizes = [35, 25, 20, 20]
fig, axs = plt.subplots(2, 2, figsize=(10,8))
# 第一个子图
axs[0,0].plot(x, y)
axs[0,0].set_title("折线图")
# 第二个子图
axs[0,1].scatter(x, y)
# 第三个子图
axs[1,0].hist(data)
# 第四个子图
axs[1,1].pie(sizes, labels=labels)
plt.tight_layout() # 自动调整间距
4.2 样式定制(StyleCustomization)
x = np.random.randn(10)
y = x * 2 + np.random.randn(10)
plt.style.use('ggplot') # 使用内置主题
fig, ax = plt.subplots()
ax.plot(x, y,
linewidth=2,
marker='D',
markersize=8,
markerfacecolor='yellow',
markeredgecolor='black')
# 设置刻度参数
ax.tick_params(axis='both',
which='major',
labelsize=12,
direction='inout')
# 设置网格线
ax.grid(True,
linestyle='--',
alpha=0.6)
# 设置坐标轴范围
ax.set_xlim(0, 10)
ax.set_ylim(-1.5, 1.5)
五、三维可视化
5.1 3D曲面图
from mpl_toolkits.mplot3d import Axes3D
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))
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z,
cmap='viridis',
antialiased=True)
fig.colorbar(surf, shrink=0.5)
六、实战案例:销售数据分析
案例1:多维度销售趋势分析
months = ['Jan', 'Feb', 'Mar', 'Apr']
sales_2023 = [120, 145, 178, 205]
sales_2024 = [135, 160, 190, None] # 模拟缺失值
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,5))
# 左侧:双折线图
ax1.plot(months, sales_2023, marker='o', label='2023')
ax1.plot(months[:3], sales_2024[:3], marker='s', label='2024')
ax1.set_title("月度销售趋势对比")
ax1.legend()
# 右侧:柱状图
ax2.bar(months, sales_2023, alpha=0.7, label='2023')
ax2.bar(months, sales_2024, alpha=0.7, label='2024',
bottom=sales_2023)
ax2.set_title("累计销售额对比")
案例2:动态交互式可视化
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'ro')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
七、高级技巧与优化
7.1 样式美化
plt.rcParams.update({
'font.family': 'SimHei', # 中文字体
'font.size': 12,
'axes.titlesize': 14,
'axes.labelsize': 12
})
7.2 输出高清图像
fig.savefig('output.png',
dpi=300, # 分辨率
bbox_inches='tight',
facecolor='white')
7.3 性能优化
- 使用
ax.plot()替代多次plt.plot() - 对于大数据集使用
numpy进行预计算 - 关闭交互模式:
plt.ioff()
八、常见问题解决方案
8.1 中文显示问题
# 方法1:指定中文字体
plt.rcParams['font.family'] = 'SimHei'
# 方法2:动态加载字体
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='msyh.ttc', size=12)
ax.set_title("标题", fontproperties=font)
8.2 坐标轴科学计数法
ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
结语
Matplotlib是数据可视化的瑞士军刀,本文涵盖了其核心功能的80%。建议通过以下方式精进:
- 每天练习一种图表类型
- 研究优秀可视化案例的源码
- 学习结合Pandas直接绘图
- 探索Seaborn等高级封装库
热门推荐
国家图书馆邀读者听广陵绝响 品千古风流
《声声慢》不是想唱就能唱 线上K歌需注意版权红线
怎么判断小孩吃药过量?这些症状需警惕
梅花为什么耐寒?
联合网贷平台诱导学员借钱培训,求职反被套路背上万元网贷
如何套用并展示员工合同模板:法律合规与操作指南
怎样快速签订合同书模板:法律实务操作指南
蓝色在HTML中的16进制表示方法及应用
兰州:让城市变花园 为生活添色彩
【神经反射疗法】肩痛的必治点
怎么鉴定离婚协议
离婚协议需要避开的三个误区
月息2分年化利率是多少
关于禅的入门,这5本书值得一读
目前的物联网操作系统都有哪些
当小股东需要注意什么事项
发现股票回撤:如何识别市场波动与回撤现象
战术板|利物浦爆冷淘汰敲响球队建设短板警钟,斯洛特想法太多了
CBA赛季前瞻:休赛期操作不断的同曦,新赛季势必冲击季后赛
肠道微生物组研究:从历史沿革到未来趋势
汽车驾驶模拟器:开启安全高效驾驶新旅程
血气分析的解读与临床应用
轻松提升手机续航与使用体验的实用技巧与设置方法
国家公务员考试科目概览:公共科目与专业科目一览表(2024版)
土木类专业留学澳洲怎么样:土木工程的四大主流就业方向及职业前景
智能车牌识别系统的设计与实现
来这感受水乡惬意,珠海沙脊村“大变身”
重庆灵活人员职工医保参保指南:条件、流程及生效时间详解
规划获批!广州火车站及周边地区改造分三步走
图文教程:3 招教你轻松制作 Ubuntu 启动盘