【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

这是机器未来的第53篇文章

原文首发地址:https://blog.csdn.net/RobotFutures/article/details/126752099

【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

; 《Python数据科学快速入门系列》快速导航:

文章目录

写在开始:

  • 博客简介:专注AIoT领域,追逐未来时代的脉搏,记录路途中的技术成长!
  • 博主社区:AIoT机器智能, 欢迎加入!
  • 专栏简介:从0到1掌握数据科学常用库Numpy、Matploblib、Pandas。
  • 面向人群:AI初级学习者

接上一篇文章:【Python数据科学快速入门系列 | 06】Matplotlib数据可视化基础入门(一)

前言

本文概述了matplotlib是什么,能做什么,怎么做的问题,是一篇matplotlib数据可视化入门文章,对于matplotlib的基础功能做了一个整体的使用说明。包含图例、轴标签、绘图区域的标签、轴的刻度、轴的范围,cmap颜色图谱映射以及注释等内容。

  1. Matplotlib的基础使用

3.2.5 添加图例标签

在同一个绘图区域内存在多个图表时,容易混淆看不清每个图标具体标识什么类型的数据,可以设置图例来标识来区分。

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 30)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.cos(2*x)

fig, ax = plt.subplots()

ax.plot(x, y1, 'go--', linewidth=2, markersize=6, label="cos(x)")

ax.plot(x, y2, 'c^:', linewidth=2, markersize=3, label="sin(x)")

ax.plot(x, y3, 'b*-.', linewidth=2, markersize=3, label="cos(2x)")

ax.legend(loc='upper right')
<matplotlib.legend.legend at 0x7fd1e0801af0>
</matplotlib.legend.legend>

【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

可以看到在右上角新增了图例区域,指定了曲线的数据函数名称。

可支持的位置配置如下:

Location StringLocation Code’best’0’upper right’1’upper left’2’lower left’3’lower right’4’right’5’center left’6’center right’7’lower center’8’upper center’9’center’10

3.2.6 设置轴的标签和图的标题

ax.set_xlable - &#x8BBE;&#x7F6E;X&#x8F74;&#x6807;&#x7B7E;
ax.set_ylabel - &#x8BBE;&#x7F6E;Y&#x8F74;&#x6807;&#x7B7E;
ax.set_title  - &#x8BBE;&#x7F6E;&#x7ED8;&#x56FE;&#x533A;&#x57DF;&#x7684;&#x6807;&#x9898;&#xFF0C;&#x5982;&#x679C;&#x8981;&#x652F;&#x6301;&#x4E2D;&#x6587;&#xFF0C;&#x9700;&#x8981;&#x505A;&#x5982;&#x4E0B;&#x914D;&#x7F6E;&#xFF1A;
plt.rcParams["font.sans-serif"]=["SimHei"]
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"]=["WenQuanYi Micro Hei"]
plt.rcParams["axes.unicode_minus"]=False

x = np.linspace(0, 2*np.pi, 30)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.cos(2*x)
y4 = np.sin(2*x)

fig, ax = plt.subplots()

ax.plot(x, y1, 'go--', linewidth=2, markersize=6, label="cos(x)")

ax.plot(x, y2, 'c^:', linewidth=2, markersize=3, label="sin(x)")

ax.plot(x, y3, 'b*-.', linewidth=2, markersize=3, label="cos(2x)")

ax.set_xlabel("Angel")

ax.set_ylabel("Value")

ax.set_title("函数示例")

ax.legend(loc='best')
<matplotlib.legend.legend at 0x7fd1e07e5ee0>
</matplotlib.legend.legend>

【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

3.2.7 设置轴的刻度值

ticks&#x6307;&#x5B9A;&#x81EA;&#x5B9A;&#x4E49;&#x7684;&#x6D6E;&#x70B9;&#x7C7B;&#x578B;&#x7684;&#x523B;&#x5EA6;&#x6807;&#x7B7E;&#x5217;&#x8868;
labels&#x6307;&#x5B9A;&#x81EA;&#x5B9A;&#x4E49;&#x7684;&#x5B57;&#x7B26;&#x4E32;&#x683C;&#x5F0F;&#x7684;&#x523B;&#x5EA6;&#x6807;&#x7B7E;&#x5217;&#x8868;&#xFF0C;&#x4E0E;ticks&#x523B;&#x5EA6;&#x503C;&#x76F8;&#x5BF9;&#x5E94;&#xFF0C;&#x53EF;&#x9009;
mininor&#x9ED8;&#x8BA4;&#x503C;&#x4E3A;False&#xFF0C;&#x5F00;&#x542F;&#x540E;&#xFF0C;&#x9ED8;&#x8BA4;&#x523B;&#x5EA6;&#x6807;&#x7B7E;&#x548C;&#x81EA;&#x5B9A;&#x4E49;&#x523B;&#x5EA6;&#x6807;&#x7B7E;&#x90FD;&#x4F1A;&#x542F;&#x7528;
ax.set_xticks(ticks, labels, minior=False)
ax.set_yticks(ticks, labels, minior=False)
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"]=["WenQuanYi Micro Hei"]
plt.rcParams["axes.unicode_minus"]=False

x = np.linspace(0, 2*np.pi, 30)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.cos(2*x)
y4 = np.sin(2*x)

fig, ax = plt.subplots()

ax.plot(x, y1, 'go--', linewidth=2, markersize=6, label="cos(x)")

ax.plot(x, y2, 'c^:', linewidth=2, markersize=3, label="sin(x)")

ax.plot(x, y3, 'b*-.', linewidth=2, markersize=3, label="cos(2x)")

ax.set_xlabel("Angel")

ax.set_ylabel("Value")

ax.set_title("函数示例")

ax.legend(loc='best')

ax.set_xticks(ticks=np.arange(0, 2*np.pi, np.pi/4), labels=[0, 'π/4', 'π/2', '3π/4', 'π', '5π/4', '3π/2', '2π'])

ax.set_yticks(ticks=[-1.0, -0.5, 0, 0.5, 1])


【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

3.2.8 设置坐标轴的范围

3.2.8.1 set_xlim和set_ylim

ax.set_ylim(bottom, top)
ax.set_xlim(left, right)

3.2.8.2 ax.set方法

ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))

3.2.8.3 ax.axis方法

ax.axis(xmin, xmax, ymin, ymax)
&#x6216;
plt.axis(xmin, xmax, ymin, ymax)
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"]=["WenQuanYi Micro Hei"]
plt.rcParams["axes.unicode_minus"]=False

x = np.linspace(0, 2*np.pi, 30)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.cos(2*x)
y4 = np.sin(2*x)

fig, ax = plt.subplots()

ax.plot(x, y1, 'go--', linewidth=2, markersize=6, label="cos(x)")

ax.plot(x, y2, 'c^:', linewidth=2, markersize=3, label="sin(x)")

ax.plot(x, y3, 'b*-.', linewidth=2, markersize=3, label="cos(2x)")

ax.set_xlabel("Angel")

ax.set_ylabel("Value")

ax.set_title("函数示例")

ax.legend(loc='best')

ax.set_xticks(ticks=np.arange(0, 2*np.pi, np.pi/4), labels=[0, 'π/4', 'π/2', '3π/4', 'π', '5π/4', '3π/2', '2π'])

ax.set_yticks(ticks=[-1.0, -0.5, 0, 0.5, 1])

ax.set(xlim=(np.pi/4, np.pi*2), ylim=(-1.5, 1.5))

(0.7853981633974483, 6.283185307179586, -1.5, 1.5)


【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

3.2.9 颜色图谱映射

2D平面图表一般数据输入是2个维度,X,Y,有时候我们需要体现3个维度,这个时候我们会将第3个维度体现在颜色上。

例如,我们现在需要做鸢尾花数据集中花萼长度和花萼宽度与鸢尾花分类的相关性分析,现在数据其实就有3个维度,花萼长度、花萼宽度、鸢尾花分类。而我们的2D图表又仅能表示2维的关系。

有个办法就是将鸢尾花分类这个维度体现在颜色上,默认情况下,颜色我们仅配置一个颜色代码,如果鸢尾花的分类具有多个分类,那么应该用不同的颜色来标识,这个时候就需要用到颜色图谱映射功能cmap。

以鸢尾花数据集中花萼长度和花萼宽度与鸢尾花分类的相关性分析为例。

import numpy as np

data = []
column_name = []
with open(file='iris.txt',mode='r') as f:

    line = f.readline()
    if line:
        column_name = np.array(line.strip().split(','))

    while True:
        line = f.readline()
        if line:
            data.append(line.strip().split(','))
        else:
            break

data = np.array(data,dtype=float)

X_data = data[:, :4]

y_data = data[:, -1]

print(data.shape, X_data.shape, y_data.shape)

plt.scatter(X_data[:,0], X_data[:,1], c=y_data, cmap='brg_r', s=10)
(150, 5) (150, 4) (150,)

<matplotlib.collections.pathcollection at 0x7fd1d69551f0>
</matplotlib.collections.pathcollection>

【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

这样就非常直观地将2种特征和标签的相关性体现出来了。

cmap支持的颜色图谱非常多,有以下两种方式获得颜色图谱代码:

  • 从官网查询可视化的颜色代码

https://matplotlib.org/stable/gallery/color/colormap_reference.html

  • 根据代码获取

import matplotlib as mpl
print(mpl.colormaps)
ColormapRegistry; available colormaps:
'magma', 'inferno', 'plasma', 'viridis', 'cividis', 'twilight', 'twilight_shifted', 'turbo', 'Blues', 'BrBG', 'BuGn', 'BuPu', 'CMRmap', 'GnBu', 'Greens', 'Greys', 'OrRd', 'Oranges', 'PRGn', 'PiYG', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Spectral', 'Wistia', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'binary', 'bone', 'brg', 'bwr', 'cool', 'coolwarm', 'copper', 'cubehelix', 'flag', 'gist_earth', 'gist_gray', 'gist_heat', 'gist_ncar', 'gist_rainbow', 'gist_stern', 'gist_yarg', 'gnuplot', 'gnuplot2', 'gray', 'hot', 'hsv', 'jet', 'nipy_spectral', 'ocean', 'pink', 'prism', 'rainbow', 'seismic', 'spring', 'summer', 'terrain', 'winter', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c', 'magma_r', 'inferno_r', 'plasma_r', 'viridis_r', 'cividis_r', 'twilight_r', 'twilight_shifted_r', 'turbo_r', 'Blues_r', 'BrBG_r', 'BuGn_r', 'BuPu_r', 'CMRmap_r', 'GnBu_r', 'Greens_r', 'Greys_r', 'OrRd_r', 'Oranges_r', 'PRGn_r', 'PiYG_r', 'PuBu_r', 'PuBuGn_r', 'PuOr_r', 'PuRd_r', 'Purples_r', 'RdBu_r', 'RdGy_r', 'RdPu_r', 'RdYlBu_r', 'RdYlGn_r', 'Reds_r', 'Spectral_r', 'Wistia_r', 'YlGn_r', 'YlGnBu_r', 'YlOrBr_r', 'YlOrRd_r', 'afmhot_r', 'autumn_r', 'binary_r', 'bone_r', 'brg_r', 'bwr_r', 'cool_r', 'coolwarm_r', 'copper_r', 'cubehelix_r', 'flag_r', 'gist_earth_r', 'gist_gray_r', 'gist_heat_r', 'gist_ncar_r', 'gist_rainbow_r', 'gist_stern_r', 'gist_yarg_r', 'gnuplot_r', 'gnuplot2_r', 'gray_r', 'hot_r', 'hsv_r', 'jet_r', 'nipy_spectral_r', 'ocean_r', 'pink_r', 'prism_r', 'rainbow_r', 'seismic_r', 'spring_r', 'summer_r', 'terrain_r', 'winter_r', 'Accent_r', 'Dark2_r', 'Paired_r', 'Pastel1_r', 'Pastel2_r', 'Set1_r', 'Set2_r', 'Set3_r', 'tab10_r', 'tab20_r', 'tab20b_r', 'tab20c_r'

3.2.10 添加注释

3.2.10.1 文本注释

可以在绘图区域的任意指定坐标显示注释, 注释支持Latex公式

x,y &#x5750;&#x6807;
s   &#x6CE8;&#x91CA;
ax.text(x, y, s, fontdict=None, **kwargs)
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"]=["WenQuanYi Micro Hei"]
plt.rcParams["axes.unicode_minus"]=False

fig, ax = plt.subplots()

ax.plot(x, y1, 'go--', linewidth=2, markersize=6, label="cos(x)")

ax.plot(x, y2, 'c^:', linewidth=2, markersize=3, label="sin(x)")

ax.plot(x, y3, 'b*-.', linewidth=2, markersize=3, label="cos(2x)")

ax.set_xlabel("Angel")

ax.set_ylabel("Value")

ax.set_title("函数示例")

ax.legend(loc='best')

ax.text(2, 0.95, "sin(x)")

plt.show()


【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

3.2.10.2 箭头文本注释

xy, &#x7BAD;&#x5934;&#x5750;&#x6807;
xytext&#xFF0C;&#x6587;&#x672C;&#x5750;&#x6807;
arrowprops&#xFF0C;&#x7BAD;&#x5934;&#x6837;&#x5F0F;
ax.annotate('local max', xy=(2.5, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05))
fig, ax = plt.subplots()

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max', xy=(2.0, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.set_ylim(-2, 2)
(-2.0, 2.0)


【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)
  1. 总结

本文总结了matplotlib基础的语法及用法,包含了安装、图的绘制、绘图样式,X、Y轴标签、图的标题、图例、注释等描述,更多高级功能详情访问matplotlib.org。

扩展思考:

matplotlib的适用边界在哪里?在哪些场景不适合用matplotlib,你知道吗?请在评论区写出你的答案。

参考文献

— 博主热门专栏推荐 —

【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

Original: https://blog.csdn.net/RobotFutures/article/details/126900121
Author: 机器未来
Title: 【Python数据科学快速入门系列 | 07】Matplotlib数据可视化基础入门(二)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/730887/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • pandas模块的基本使用

    numpy能够帮助我们处理数值,但是pandas除了能处理数值之外(基于numpy),还能够帮助我们处理其他类型的数据pandas技术文档:https://pandas.pydat…

    Python 2023年8月9日
    063
  • Python + Flask ORM实现增删改查

    1. 背景介绍 SQLAlchemy 以 ORM 为核心基础提供可选对象关系映射能力。 (1). ORM 提供一个附加的配置层,允许用户自定义的 Python 类进行对象关系映射,…

    Python 2023年5月25日
    076
  • 18.聚合查询和原生数据库语句操作

    目录 1 聚合查询 1.1 聚合函数 1.2 整表聚合 1.3 分组聚合 2 原生数据库操作 2.1 仅查询 raw() 2.2 查询,更新与删除 cursor 2.2.1 查询 …

    Python 2023年8月4日
    050
  • 打包python程序成exe

    安装pyinstaller 直接在cmd使用pip命令安装pyinstaller。 pip install pyinstaller 如果因为网速问题安装失败可以尝试使用国内源。 p…

    Python 2023年9月22日
    029
  • K-means聚类算法一文详解+Python代码实例

    抵扣说明: 1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。 Original: https://blo…

    Python 2023年7月31日
    046
  • H5文件批量读写操作

    1、遍历文件夹操作 for root, dirs, files in os.walk(file_location): # root&#x8F93;&#x51FA;&…

    Python 2023年8月21日
    041
  • C语言必背18个经典程序

    1、/输出99口诀。共9行9列,i控制行,j控制列。*/ #include "stdio.h" main() {int i,j,result; for(i=1;…

    Python 2023年10月11日
    034
  • 设计模式—抽象工厂模式

    类型:创建型 目的:实现对客户端中 对象族的平替。 对象族具有共同主题的一组对象的集合。比如,华为的手机,笔记本,平板可以统称为华为族。 我们借以下案例来说说如何使用抽象工厂模式平…

    Python 2023年10月20日
    032
  • 数据分析之实例一:餐厅订单数据分析

    实例一:餐厅订单数据分析 #&#x5148;&#x8FDB;&#x884C;&#x8BBE;&#x7F6E; import pandas a…

    Python 2023年8月7日
    068
  • Superset系列1-Superset简介

    Superset是Airbnb开源BI数据分析与可视化平台(曾用名Caravel、Panoramix),该工具主要特点是可自助分析、自定义仪表盘、分析结果可视化(导出)、用户/角色…

    Python 2023年8月12日
    034
  • 简单看懂编译链接

    在这里,我想任何人做编程相关的人都应该至少接触过某种编程语言,接触过程序的编译,执行过自己源代码产生的可执行文件。对于可执行文件我想不得不提需要关心的应该直接首先是两个: 1.可执…

    Python 2023年10月20日
    032
  • 初识Python系列(一)

    对于Python selenium操作的总结(一) 1.对于驱动的安装 驱动包:webdriver(在cmd执行help(webdriver)可查看所支持的浏览器类型,在此只提其中…

    Python 2023年5月24日
    067
  • 推荐系统笔记(五):lightGCN算法原理与背景

    背景 lightGCN是将图卷积神经网络应用于推荐系统当中,是对神经图协同过滤(NGCF)算法的优化和改进。lightGCN相比于其对照算法提升了16%左右,在介绍lightGCN…

    Python 2023年8月2日
    043
  • YOLOv5-6.1添加注意力机制(SE、CBAM、ECA、CA)

    目录 0. 添加方法 1. SE * 1.1 SE 1.2 C3-SE 2. CBAM * 2.1 CBAM 2.2 C3-CBAM 3. ECA * 3.1 ECA 3.2 C3…

    Python 2023年7月31日
    0151
  • Python之初识Pandas

    Pandas Pandas的功能Pandas提供了高级数据结构和数据操作工具,它是使Python成为强大而高效的数据处理环境的重要因素之一。 Numpy能够帮助我们处理数值,但是p…

    Python 2023年8月8日
    049
  • 在一维的世界里寻找迭代次数的影子

    ( A, B )—1302—( 1, 0 )( 0, 1 ) 让网络的输入只有1个节点,AB各由3张二值化的图片组成,排列组合A和B的所有可能性,固定收敛误…

    Python 2023年10月7日
    045
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球