栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 数据分析——Matplotlib相关知识

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 数据分析——Matplotlib相关知识

Python 数据分析——Matplotlib相关知识

文章目录
  • Python 数据分析——Matplotlib相关知识
  • 前言
  • 一、Matplotlib安装
  • 二、使用步骤
  • 三、关于Figure的组成
  • 四、两种最常用的绘图
  • 五、通用模板
  • 六、参考


前言

主要写一下关于Python数据分析中关于matplotlib的一些具体使用


一、Matplotlib安装

简介: 具体可以查看Matplotlib官方文档
我们只需了解Matplotlib是Python的一种2D绘图库,可以绘制所需的散点图、柱状图、条形图等等动静、交互的图表
安装: 两种方式

# 使用pip
pip install matplotlib

# 使用conda
conda install matplotlib

验证: 进入Python输入import matplotlib,若无报错即成功

二、使用步骤

简单例子

代码如下(示例):

# 导入库
import matplotlib.pyplot as plt
import matplotlib as mpl
# 绘制一个简单图标
fig, ax = plt.subplots()  # 创建一个包含一个axes的figure
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]);  # 绘制图像
# 或简单的写
line =plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) 

三、关于Figure的组成

可以参考官方文档提供的图

  • Figure:顶层级,用来容纳所有绘图元素
  • Axes:matplotlib宇宙的核心,容纳了大量元素用来构造一幅幅子图,一个figure可以由一个或多个子图组成
  • Axis:axes的下属层级,用于处理所有和坐标轴,网格有关的元素
  • Tick:axis的下属层级,用来处理所有和刻度有关的元素

四、两种最常用的绘图

matplotlib提供了两种最常用的绘图

  • 显式创建figure和axes,在上面调用绘图方法,也被称为OO模式(object-oriented style)
x = np.linspace(0, 2, 50)  # 在(0,2)之间生成均匀的点

fig, ax = plt.subplots(figsize=(5, 2.7),layout='constrained')
# 绘制三条不同的线
ax.plot(x, x, label='linear')  
ax.plot(x, x**2, label='quadratic')  
ax.plot(x, x**3, label='cubic')  

ax.set_xlabel('x label')  # 横坐标标签
ax.set_ylabel('y label')  # 纵坐标标签
ax.set_title("Simple Plot")  # 图标题
ax.legend();  

  • 依赖pyplot自动创建figure和axes,并绘图
x = np.linspace(0, 2, 50) 

fig, ax = plt.subplots(figsize=(5, 2.7),layout='constrained')
plt.plot(x, x, label='linear')  
plt.plot(x, x**2, label='quadratic') 
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();

结果一致:

五、通用模板

Matplotlib绘图的主要基本步骤:

1. 准备数据
2. 设置绘图样式,这一步并非必须
3. 定义布局
4. 绘制图像
5. 添加标签、文字和图例

参考Matplotlib基本用法的官方文档可以总结出上述所说的两种绘图方式模板

  • OO 模式绘图模板
# step1 准备数据
x = np.linspace(0, 2, 100)
y = x**2

# step2 设置绘图样式
mpl.rc('lines', linewidth=4, linestyle='-.')

# step3 定义布局
fig, ax = plt.subplots()  

# step4 绘制图像
ax.plot(x, y, label='linear')  

# step5 添加标签,文字和图例
ax.set_xlabel('x label') 
ax.set_ylabel('y label') 
ax.set_title("Simple Plot")  
ax.legend() ;
  • pyplot 绘图模板
# step1 准备数据
x = np.linspace(0, 2, 100)
y = x**2

# step2 设置绘图样式
mpl.rc('lines', linewidth=4, linestyle='-.')

# step3 绘制图像
plt.plot(x, y, label='linear')  

# step4 添加标签,文字和图例
plt.xlabel('x label') 
plt.ylabel('y label') 
plt.title("Simple Plot")  
plt.legend() ;
六、参考

本次主要参考学习了Datawhale数据可视化的Matplotlib教程以及Matplotlib的官方文档

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号