Matplotlib完全指南:数据可视化从入门到实战
创作时间:
作者:
@小白创作中心
Matplotlib完全指南:数据可视化从入门到实战
引用
CSDN
1.
https://blog.csdn.net/qq_67342067/article/details/146375242
Matplotlib是Python最强大的数据可视化库,可以创建高质量的2D/3D图形,完美支持科学计算与数据分析。本文将深入讲解Matplotlib的核心功能,通过20+个实战案例,带你从基础绘图到高级可视化技巧,全面掌握数据图形化表达!
引言
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等高级封装库
热门推荐
玻璃磨边切屑的控制方法
如何通过简单的视觉效果调整,让你的PPT焕发新生?
全国高考本科录取率预测,上海达到77%,湖北仅35.3%!
麦克阿瑟离开日本时,为什么会引发50万民众送别?
微孔滤芯过滤器怎么用
猪苓的功效与应用
汉堡制作:从食材准备到组装的美味之旅
浙川一家亲,共铸山海情丨三年浙川协作,筑起一个个致富产业!
《儿童腺样体肥大诊治专家共识》项目定稿会圆满落幕
Live Stream是什么意思?详解直播流技术原理与应用
面试中如何巧妙回答薪资期望问题
科技布沙发使用两年后的真相:这些坑你一定要知道!
律师职业的基本要求有哪些
中国未来30年的经济重心,将全面南移,宁波已开始全面反超天津!
守一守静:道家修炼的核心方法
申花4-2大胜神户未能晋级淘汰赛,这不是一场胜利却是中超的胜利
超大场景的三维模型(3D)轻量化的主要技术方法
K-12学生的暑期学习计划:如何利用假期提升成绩
惠评文旅|大S日本流感病逝引发退订潮:从反脆弱理论看日本旅游市场的韧性
票房破百亿!专访《哪吒2》主创 解锁成功密码
“宫廷玉液酒,一百八一杯”:赵丽蓉的艺术人生
文学的青春表达
祛痣想要不留疤,选激光还是手术切除?
文档管理完全指南:从基础到未来趋势
打旅居牌的江南小城,看中不上班的数字游民
婚后买房怎样能归一方所有财产
抢手的教育地产指南:怎样为孩子选到优质学区房?
如何优雅地合并两个有序数组:从基础到进阶的解法探索
如何将素书的教诲融入工作中
洛阳三日游,超详细行程安排来了!玩转洛阳必看