Python3 模块精讲:Matplotlib—— 数据可视化、绘图从零基础到实战精通
文章标签#Python #Matplotlib #数据可视化 #数据分析 #AI 人工智能 #零基础学 Python前言在人工智能、数据分析、机器学习领域数据可视化是最核心的呈现方式。Matplotlib 是 Python 中最经典、最稳定、最通用的 2D 绘图库几乎所有数据分析、AI 训练、论文绘图都会用到。本文专为零基础小白打造从安装→基础绘图→进阶美化→AI 实战→常见问题全程代码可直接复制运行每一段代码都带详细注释每一张图都已生成并展示不讲废话、只讲实战让你快速掌握 Matplotlib 绘图全技能一、Matplotlib 基础认知1.1 什么是 MatplotlibMatplotlib 是 Python 的2D 绘图库可以绘制折线图、散点图、柱状图、直方图、饼图、热力图、3D 图、等高线图等。它是数据科学、AI、机器学习、办公自动化必备工具。1.2 Matplotlib 核心优势免费开源、轻量高效低配电脑可流畅运行语法简单、零基础快速上手高度自定义可做出论文级图表与 NumPy、Pandas、AI 框架完美兼容支持高清导出 PNG、PDF、SVG1.3 核心架构极简理解Figure 画布整张图的容器Axes 坐标系真正绘图的区域Axis 坐标轴X 轴、Y 轴plt.plot()绘图plt.show()显示图片plt.savefig()保存图片二、环境安装与基础配置必看2.1 安装命令无报错版bash运行pip install matplotlib numpy -i https://pypi.tuna.tsinghua.edu.cn/simple2.2 全局中文配置解决中文乱码python运行import matplotlib.pyplot as plt import numpy as np # -------------------------- 【全局配置】 -------------------------- plt.rcParams[font.sans-serif] [SimHei] # 中文显示 plt.rcParams[axes.unicode_minus] False # 负号显示 plt.rcParams[axes.grid] True # 默认网格 plt.rcParams[grid.alpha] 0.3 # 网格透明度 plt.rcParams[figure.figsize] (10, 6) # 画布大小 plt.rcParams[figure.dpi] 100 # 画布分辨率三、基础绘图5 大核心图表全代码 全注释 全运行 全图3.1 折线图 plt.plot () —— 趋势展示最常用实战 1年龄趋势图python运行import matplotlib.pyplot as plt import numpy as np # 配置中文 plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False plt.rcParams[axes.grid] True plt.rcParams[grid.alpha] 0.3 # 数据 ages [13岁,14岁,15岁,16岁,17岁,18岁,19岁,20岁,21岁,22岁,23岁,24岁,25岁,26岁,27岁] values [1,1,2,4,3,2,3,4,4,5,6,5,4,3,3] # 创建画布 plt.figure(figsize(12,6)) # 绘制折线 plt.plot(ages, values, color#1f77b4, linewidth2.5, markero, markersize6, label数值) # 图表装饰 plt.title(年龄分布趋势折线图, fontsize16) plt.xlabel(年龄, fontsize12) plt.ylabel(统计数值, fontsize12) plt.xticks(rotation30) plt.legend() plt.grid(alpha0.3) # 保存 显示 plt.tight_layout() plt.savefig(age_trend.png, dpi300, bbox_inchestight) plt.show()3.2 双折线对比图正弦 余弦python运行import matplotlib.pyplot as plt import numpy as np plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 生成数据 x np.linspace(0, 10, 100) y_sin np.sin(x) y_cos np.cos(x) # 绘图 plt.figure(figsize(10,6)) plt.plot(x, y_sin, labelsin(x), color#1f77b4, linewidth2) plt.plot(x, y_cos, labelcos(x), color#ff7f0e, linewidth2, linestyle--) # 装饰 plt.title(正弦余弦函数对比曲线, fontsize14) plt.xlabel(X轴, fontsize12) plt.ylabel(Y轴, fontsize12) plt.legend() plt.grid(alpha0.3) plt.savefig(sin_cos.png, dpi300) plt.show()3.3 散点图 plt.scatter () —— 数据相关性分析python运行import matplotlib.pyplot as plt import numpy as np plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 构造数据 np.random.seed(42) x np.linspace(0,10,100) y 2 * x np.random.randn(100) * 2 # 绘制散点图 plt.figure(figsize(10,6)) plt.scatter(x, y, color#2ca02c, s60, alpha0.7, label样本点) # 装饰 plt.title(散点图X与Y线性关系, fontsize14) plt.xlabel(自变量X, fontsize12) plt.ylabel(因变量Y, fontsize12) plt.legend() plt.grid(alpha0.3) plt.savefig(scatter.png, dpi300) plt.show()生成图形3.4 柱状图 plt.bar () —— 分类数据对比python运行import matplotlib.pyplot as plt plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 数据 names [产品A,产品B,产品C,产品D,产品E] sales [45,62,38,75,52] colors [#1f77b4,#ff7f0e,#2ca02c,#d62728,#9467bd] # 绘图 plt.figure(figsize(10,6)) bars plt.bar(names, sales, colorcolors) # 给柱子添加数值 for bar in bars: h bar.get_height() plt.text(bar.get_x()bar.get_width()/2, h1, f{h}, hacenter, fontsize12) # 装饰 plt.title(产品销量对比柱状图, fontsize14) plt.xlabel(产品类型) plt.ylabel(销量件) plt.grid(axisy, alpha0.3) plt.savefig(bar_sales.png, dpi300) plt.show()生成图形3.5 直方图 plt.hist () —— 数据分布统计python运行import matplotlib.pyplot as plt import numpy as np plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 生成正态分布数据 data np.random.normal(loc0, scale1, size10000) # 绘图 plt.figure(figsize(10,6)) plt.hist(data, bins50, color#1f77b4, edgecolorblack, alpha0.7) # 装饰 plt.title(正态分布直方图10000样本, fontsize14) plt.xlabel(数值) plt.ylabel(频数) plt.grid(alpha0.3) plt.savefig(hist.png, dpi300) plt.show()3.6 饼图 plt.pie () —— 占比分析python运行import matplotlib.pyplot as plt plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 数据 labels [手机端,PC端,平板端,其他] sizes [65,22,10,3] colors [#ff9999,#66b3ff,#99ff99,#ffcc99] explode (0.05,0,0,0) # 绘图 plt.figure(figsize(8,8)) plt.pie(sizes, explodeexplode, labelslabels, colorscolors, autopct%1.1f%%, shadowTrue, startangle90) plt.axis(equal) plt.title(用户设备使用占比饼图, fontsize14) plt.savefig(pie.png, dpi300) plt.show()四、Matplotlib 进阶绘图AI / 工作必备4.1 多子图 subplots一图多表python运行import matplotlib.pyplot as plt import numpy as np plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 创建2行2列子图 fig, axs plt.subplots(2, 2, figsize(12,8)) x np.linspace(0,10,100) axs[0,0].plot(x, np.sin(x), color#1f77b4) axs[0,0].set_title(正弦函数) axs[0,0].grid(True, alpha0.3) axs[0,1].plot(x, np.cos(x), color#ff7f0e) axs[0,1].set_title(余弦函数) axs[0,1].grid(True, alpha0.3) axs[1,0].plot(x, np.exp(-x/5), color#2ca02c) axs[1,0].set_title(指数衰减) axs[1,0].grid(True, alpha0.3) axs[1,1].plot(x, np.sqrt(x), color#d62728) axs[1,1].set_title(平方根函数) axs[1,1].grid(True, alpha0.3) plt.tight_layout() plt.savefig(subplots.png, dpi300) plt.show()4.2 AI 模型训练曲线最常用实战python运行import matplotlib.pyplot as plt import numpy as np plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False # 模拟训练数据 epochs np.arange(1,51) train_loss 0.8 * np.exp(-epochs/10) val_loss 0.9 * np.exp(-epochs/12) train_acc 0.5 0.48*(1-np.exp(-epochs/8)) val_acc 0.45 0.45*(1-np.exp(-epochs/10)) # 创建双图 fig, (ax1, ax2) plt.subplots(1,2, figsize(14,5)) ax1.plot(epochs, train_loss, label训练损失, linewidth2) ax1.plot(epochs, val_loss, label验证损失, linewidth2, linestyle--) ax1.set_title(损失曲线, fontsize12) ax1.set_xlabel(Epoch, fontsize10) ax1.set_ylabel(Loss, fontsize10) ax1.legend() ax1.grid(True, alpha0.3) ax2.plot(epochs, train_acc, label训练准确率, colorgreen, linewidth2) ax2.plot(epochs, val_acc, label验证准确率, colorred, linewidth2, linestyle--) ax2.set_title(准确率曲线, fontsize12) ax2.set_xlabel(Epoch, fontsize10) ax2.set_ylabel(Accuracy, fontsize10) ax2.legend() ax2.grid(True, alpha0.3) plt.suptitle(AI模型训练可视化, fontsize14) plt.tight_layout() plt.savefig(ai_training.png, dpi300) plt.show()五、Matplotlib 高级美化技巧5.1 线条样式设置python运行plt.plot(x,y, linestyle-) # 实线 plt.plot(x,y, linestyle--) # 虚线 plt.plot(x,y, linestyle:) # 点线 plt.plot(x,y, markero) # 圆点 plt.plot(x,y, markers) # 方块5.2 颜色设置python运行colorred color#1f77b4 color#ff7f0e5.3 高清导出python运行plt.savefig(图.png, dpi300, bbox_inchestight)5.4 画布大小python运行plt.figure(figsize(10,6))六、零基础常见问题100% 解决6.1 中文显示方框python运行plt.rcParams[font.sans-serif] [SimHei]6.2 图片不显示python运行plt.show()6.3 保存图片空白必须先保存后显示python运行plt.savefig(a.png) plt.show()6.4 标签重叠python运行plt.xticks(rotation30)七、总结超完整版本文从零基础带你掌握Matplotlib 安装与中文配置5 大基础图表折线 / 散点 / 柱状 / 直方图 / 饼图多子图、AI 训练曲线、高清导出商务风格、论文风格、AI 风格绘图所有代码可直接运行、无报错、全注释所有图表已实际生成、清晰美观只要跟着本文练习3 天你就能独立完成✅ 数据分析图表✅ AI 模型训练曲线✅ 商务报表图表✅ 论文高清插图✅ 自动化办公绘图