机器学习学习笔记01_matplotlib绘图

2023-05-16

导入需要的库

import matplotlib.pyplot as plt
import numpy as np
from jupyterthemes import jtplot
jtplot.style(grid=False)

建立xy对应关系

x = np.linspace(-2, np.pi)
y1 = np.sin(x)
y2 = np.cos(x)

plot()

matplotlib.pyplot.plot()参数详解
https://matplotlib.org/api/pyplot_summary.html

#单条线:
plot([x], y, [fmt], data=None, **kwargs)
#多条线一起画
plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)

plt.figure(num=2,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show()

在这里插入图片描述

plt.xlim(), plt.ylim()

确定显示的xy范围

plt.figure(num=2,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
plt.savefig("1.png")
plt.show()

修改x, y轴的标签

new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r’ n n n’,r’ n r nr nr’,r’ s s s’,r’ s r sr sr’,r’ s s r ssr ssr’])

plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$n$',r'$nr$',r'$s$',r'$sr$',r'$ssr$'])
plt.show()

修改边框

ax = plt.gca()
ax.spines[‘你想要修改的边’].set_color(‘none’)

修改坐标轴位置

ax.xaxis.set_ticks_position(‘bottom’)
ax.spines[‘bottom’].set_position((‘data’,0))

ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘left’].set_position((‘data’,0))

plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$n$',r'$nr$',r'$s$',r'$sr$',r'$ssr$'])

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))

ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

plt.show()

小练习

import matplotlib.pyplot as plt
import numpy as np

from jupyterthemes import jtplot
jtplot.style(grid=False)

#设置样式
plt.style.use(plt.style.available[1])

#显示中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#用来正常显示负号
plt.rcParams['axes.unicode_minus']=False

x = np.linspace(-2, 3)
y = x-1

#画线,lable是线条的标签
plt.plot(x,y,color='blue',linewidth=1.0,linestyle='--',label='y=x-1')

plt.xlim((-1,2))
plt.ylim((-2,1))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-1,-0.5,1],[r'$bad$',r'$normal$',r'$good$'])

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))

ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

#显示标题
plt.title(r'数据可视化小练习')

#添加图例,将label与对应关系显现出来
plt.legend(loc='best',edgecolor='green')

#保存图片
plt.savefig("数据可视化.png")

plt.show()

在这里插入图片描述

Annotation 标注

当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法,一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注。首先回顾一下上一章节的画图教程:

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5),)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
plt.plot(x, y,)

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
<matplotlib.collections.PathCollection at 0x1bf13d48ac8>

在这里插入图片描述

添加注释 annotate

接下来我们就对(x0, y0)这个点进行标注。第一种方式就是利用函数 annotate(),其中 r’’ %y0 代表标注的内容,可以通过字符串 %s 将 y0 的值传入字符串;参数xycoords=‘data’ 是说基于数据的值来选位置, xytext=(+30, -30) 和 textcoords=‘offset points’ 表示对于标注位置的描述 和 xy 偏差值,即标注位置是 xy 位置向右移动 30,向下移动30, arrowprops是对图中箭头类型和箭头弧度的设置,需要用 dict 形式传入。

plt.figure(num=1, figsize=(8, 5),)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
plt.plot(x, y,)

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
Text(30,-30,'$2x+1=3$')

(img-4fXVKph6-1601519009565)(output_17_1.png)]

添加注释 text

第二种注释方式是通过text()函数

plt.figure(num=1, figsize=(8, 5),)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
plt.plot(x, y,)

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})
Text(-3.7,3,'$This\\ is\\ the\\ some\\ text. \\mu\\ \\sigma_i\\ \\alpha_t$')

在这里插入图片描述

plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2,label='cos x')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='sin x')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$n$',r'$nr$',r'$s$',r'$sr$',r'$ssr$'])

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))

ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

plt.legend(loc='best',edgecolor='brown')

plt.show()

在这里插入图片描述

plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,1])

plt.subplot(2,3,5)
plt.plot([0,1],[0,1])

plt.subplot(2,3,6)
plt.plot([0,1],[0,1])
[<matplotlib.lines.Line2D at 0x223d1011748>]

在这里插入图片描述

ax1 = plt.subplot2grid((3,3),(0,0),colspan=3)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')

ax2 = plt.subplot2grid((3,3),(1,0),colspan=2)

ax3 = plt.subplot2grid((3,3),(1,2),rowspan=3)

ax4 = plt.subplot2grid((3,3),(2,0))

ax5 = plt.subplot2grid((3,3),(2,1))

ax4.scatter([1,2],[2,2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
Text(0,0.5,'ax4_y')

在这里插入图片描述

f,((ax11,ax12),(ax13,ax14)) = plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2], [1,2])
<matplotlib.collections.PathCollection at 0x20fe72b4358>

使用同一刻度线

twinx()函数表示共享x轴
twiny()表示共享y轴
共享表示的就是x轴使用同一刻度线

python—之suplot里面的twinx()函数
ax2 = ax1.twinx()

fig,ax1 = plt.subplots()

ax2 = ax1.twinx()

ax1.plot(x,y1,‘g-’)
ax1.set_xlabel(‘X data’)
ax1.set_ylabel(‘Y1 data’, color=‘g’)
ax2.plot(x, y2, ‘b-’) # blue
ax2.set_ylabel(‘Y2 data’, color=‘b’)

练一练

方法一 plt.subplot

#设置样式
plt.style.use(plt.style.available[0])

#显示中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#用来正常显示负号
plt.rcParams['axes.unicode_minus']=False

plt.figure(figsize=(6,6))

plt.suptitle('练一练')

x = np.linspace(-3, 3)
y = x

plt.subplot(2,2,1)
plt.plot(x,y,label='y = x',color='grey')
plt.legend(loc='best',edgecolor='brown')


y = x**2

plt.subplot(2,2,2)
plt.plot(x,y,label='y = x^2',color='b')
plt.legend(loc='best',edgecolor='brown')


y = 0.01*x - 0.01

plt.subplot(2,1,2)
plt.plot(x,y,label='y=0.01*x-0.01',color='r')
plt.legend(loc='best',edgecolor='brown')

<matplotlib.legend.Legend at 0x1bf0f1b41d0>

方法二 plt.subplots

#设置样式
plt.style.use(plt.style.available[21])

#显示中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#用来正常显示负号
plt.rcParams['axes.unicode_minus']=False

f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=False, sharey=False,figsize=(6, 6))

plt.suptitle('练一练')

x = np.linspace(-3, 3)
y = x

ax11.plot(x,y,label='y = x',color='grey')
ax11.legend(loc='best',edgecolor='brown')

y = x**2

ax12.plot(x,y,label='y = x^2',color='b')
ax12.legend(loc='best',edgecolor='brown')

y = 0.01*x - 0.01

plt.subplot(2,1,2)
plt.plot(x,y,label='y=0.01*x-0.01',color='r')
plt.legend(loc='best',edgecolor='brown')
<matplotlib.legend.Legend at 0x1bf13c57908>

方法三 plt.subplot2grid

#设置样式
plt.style.use(plt.style.available[11])

#显示中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#用来正常显示负号
plt.rcParams['axes.unicode_minus']=False

plt.figure(figsize=(6, 6))

plt.suptitle('练一练')

x = np.linspace(-3, 3)
y = x

ax1 = plt.subplot2grid((2,2),(0,0),colspan=1)
ax1.plot(x,y,label='y = x',color='grey')
ax1.legend(loc='best',edgecolor='brown')

y = x**2
ax2 = plt.subplot2grid((2,2),(0,1),colspan=1)
ax2.plot(x,y,label='y = x^2',color='b')
ax2.legend(loc='best',edgecolor='brown')

y = 0.01*x - 0.01

ax2 = plt.subplot2grid((2,2),(1,0),colspan=2)
ax2.plot(x,y,label='y=0.01*x-0.01',color='r')
ax2.legend(loc='best',edgecolor='brown')
<matplotlib.legend.Legend at 0x1bf11fdfd68>

(img-8raqM51w-1601519009572)(output_32_1.png)]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

机器学习学习笔记01_matplotlib绘图 的相关文章

随机推荐

  • Debian10安装

    Debian 10 7 buster 使用bt文件下载 下载链接 xff1a https cdimage debian org debian cd current amd64 bt dvd 这次是在VMware Workstation上安装
  • Debian——网络/镜像配置

    文章目录 前言一 添加镜像源二 配置网络三 添加阿里云镜像 前言 安装完成之后 xff0c 配置apt源和网络 提示 xff1a 以下是本篇文章正文内容 xff0c 下面案例可供参考 一 添加镜像源 添加ISO文件 xff0c 并连接 ap
  • [Arch iwlist issue] Allocation failed

    之前在学校用 networkmanager 一直不好用 所以试了试手动调试 谁知道再用 iwlist scan时出错 allocation failed 查了一下google 原来是个bug 在无线太多环境下 xff0c 就会出现这种情况
  • 执行pth-winexe报错:ERROR: CreateService failed. NT_STATUS_ACCESS_DENIED.

    问题 xff1a 执行pth winexe时报错 xff1a pth winexe U test aad3b435b51404eeaad3b435b51404ee afc44ee7351d61d00698796da06b1ebf 192 1
  • Windows 远程端口号修改

    远程桌面端口号修改 xff1a 1 计算机 HKEY LOCAL MACHINE SYSTEM CurrentControlSet Control Terminal Server Wds rdpwd Tds tcp 修改PortNumber
  • CCSP2016-1 选座(ticket_chooser)

    CCSP2016 1 选座 xff08 ticket chooser xff09 题目描述 小 B 是一个电影迷 xff0c 只要有时间 xff0c 她就要去观摩最新的大片 但她不喜欢自己在 电脑或其他电子设备上观看 xff0c 而是喜欢去
  • manjaro配置VNC服务

    硬件 xff1a 开发板 xff1a Raspberry Pi 树莓派4B 4G内存 电脑 xff1a win10主机 系统 xff1a manjaro xff1a Raspberry Pi 4 KDE Plasma 21 06 一些准备工
  • iOS开发:关于UISearchController的简单使用

    UISearchController是iOS8以后推出的一个控件 xff0c 在以前的搜索控制器中 xff0c 需要将searchBar于tableView结合使用 有了这个控件之后 xff0c 做搜索控制器就很简单了 效果图 一 需要遵守
  • mac访问win7共享文件夹

    看了网上的一些操作步骤不是太详尽 xff08 对 xff0c 我就是嫌弃它图少 xff09 xff0c 特地制作一个教程来教大家使用mac访问win7的共享文件夹 一 首先我们创建一个用于测试的文件夹 我的台式电脑撤出来一根网线连接在了路由
  • DllNotFoundException

    检查运行dll是否需要其他的dll 这个是报错比较常见的原因 在Unity中报DllNotFoundException有可能是找不到的dll xff0c 它需要引用的其他dll不存在 这个不仅仅是适用于Unity xff0c 大多数dll的
  • Steam游戏的爬取与分析

    Steam游戏的爬取与分析 本文爬取了steam冒险类游戏中热销产品中的7500个游戏进行统计分析 1 首先要先知道网页链接的组成形式 xff1a 2 其次查看我们想要爬取的信息区域 xff1a 3 开始分析 xff1a xff08 1 x
  • word里面的自带编辑器公式怎么转换成math type公式

    这是最近产生的一个问题 xff0c 还在解决中 已解决 这个问题出现主要是因为老板要编书 xff0c 然后一开始是让我们用word自带的编辑器进行编辑 xff0c 现在突然变化 xff0c 让我们全部改成math type格式 首先百度ma
  • Ubuntu 20.04 无法解析软件包文件 /var/lib/dpkg/status

    出现问题 E 无法解析软件包文件 var lib dpkg status 1 W 您可能需要运行 apt get update 来解决这些问题 E 软件包缓存文件损坏了 截图 xff1a 这东西我试了前辈的博客的方法 xff0c 瞎套果然不
  • 如何进入Ubuntu 18.04.1 LTS的根目录

    Ubantu虽然在文件操作上已经有了比较完善的桌面版 xff0c 但是有时候我们想在文件夹找到某一目录还是很难找到的 这个时候我们可以先到根目录下 xff0c 然后在依次查找相应文件夹 另外 xff0c 此操作对于不习惯或者不会使用vi或者
  • Linux下V4L2调用摄像头设备程序崩溃

    问题描述 使用V4L2驱动调用摄像头 xff0c 只能打开一次摄像头 xff0c 第二次打开时程序崩溃 原因 在获取相机数据流时我们一般会使用mmap 来将linux内核空间映射到用户空间 xff0c 在关闭相机时应当调用munmap 解除
  • 时钟恢复(CDR:Clock and Data Recovery)和PLL/DLL

    CDR的作用及应用场景 CDR的主要有两大作用 xff0c 第一是为接收器端各电路提供时钟信号 xff1b 第二是对接收到的信号进行判决 xff0c 便于数据信号的恢复与后续处理 CDR在各种高速PHY RX的应用 xff1a 比如高速ph
  • 【MathType安装】2020年最新将MathType加入word的方法,解决"运行时错误53,MathPage.wll文件未找到"问题

    2020年最新的将MathType加入word的方法 1 找到你的 STARTUP 文件夹2 打开MathType的安装路径3 在word中选择加载4 完成 1 找到你的STARTUP文件夹 这里我提供的方法是下载一个everything搜
  • 【WPF大作业】记一次C#大作业——商家快递包裹系统

    WPF XAML商家快递包裹系统 一 前言二 采用的框架三 程序设计以及架构四 界面一览登录界面主界面统计页面处理订单添加订单物流查询 五 特色功能1 自定义的带花纹的顶栏2 数据库的连接与利用3 选项卡页面4 同步修改表格数据5 任务栏图
  • 熟悉常用的Linux操作和Hadoop操作

    cd命令 xff1a 切换目录 xff08 1 xff09 切换到目录 usr local xff08 2 xff09 去到目前的上层目录 xff08 3 xff09 回到自己的主文件夹 ls命令 xff1a 查看文件与目录 xff08 4
  • 机器学习学习笔记01_matplotlib绘图

    导入需要的库 span class token keyword import span matplotlib span class token punctuation span pyplot span class token keyword