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等高级封装库
热门推荐
香港黑帮片“教父”,推荐10部杜琪峰执导的高分电影
香港黑帮片“教父”,推荐10部杜琪峰执导的高分电影
eSIM使用指南:工作原理、应用场景、设备支持及设置方法
带鱼为什么要刮鱼鳞
鸭血的营养成分
房车租赁合同指南:从主体信息到违约责任详解
你真的懂底盘么?——底盘的调校与测试
枸杞和六味地黄丸能一起吃吗?医生这样建议
日本投降书上的中国名字:为什么签字代表是徐永昌?
从《甄嬛传》谈檀香养心
【檀香】是甚麼? 一文講清楚檀香的特點、味道、產地和歷史文化背景。
“光辉时代”闭幕倒计时|达·芬奇旷世杰作的“姐妹篇”:普拉多的《蒙娜丽莎》
吃得好≠营养够!点外卖也要学会科学搭配,让营养更加均衡
火上热搜的蛇瓜究竟是什么瓜?还是来自印度?
遵义至重庆武隆交通指南:全程公里数、行车路线及预计时间
结息是属于扣钱还是返还?一文读懂金融中的"结息"概念
网上起诉离婚开庭需要双方到场
九华山个人自由行旅游全攻略
黑色汉服:秋日里的高级时尚宣言
多地端午节庆活动扫描:缅怀·传承·弘扬
《剑星》获M站9.2高分,但仍因"和谐"引发玩家争议
去除视频水印是否构成侵权:探讨去水印服务的法律问题
爱迪生:天才发明家与企业家的传奇人生
巧用废旧iPad!轻松改造成家庭电子相册
钛的硬度:特性、影响因素及应用领域
如何引导14岁孩子控制情绪:方法与策略
萝卜和西洋参能不能一起吃
西洋参虽好,却不能“随便吃”,5个注意事项要牢记
高考分数查询指南及300-400分考生报考建议
大人长智齿牙龈肿痛怎么办?专业医生这样建议