侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python绘制双Y轴折线图以及单Y轴双变量柱状图的实例

Python  /  管理员 发布于 7年前   191

近来实验室的师姐要发论文,由于论文交稿时间临近,有一些杂活儿需要处理,作为实验室资历最浅的一批,我这个实习生也就责无旁贷地帮忙当个下手。今天师姐派了一个小活,具体要求是:

给一些训练模型的迭代次数,训练精度的数据,让我做成图表形式展示出来,一方面帮助检查模型训练时的不足,另一方面来看样本数目和预测精度之间的联系,数据具体格式如下:

Iteration 1500label train test  right acc12  143 24  24  1.0160 92  16  15  0.9375100 12  2   0   0.0142 0   0   0   0.0152 0   0   0   0.0110 10  2   0   0.0170 12  2   2   1.042  421 70  63  0.931  43  8   5   0.62522  132 22  18  0.81818181818260  51  9   8   0.88888888888951  916 153 143 0.934640522876131 82  14  11  0.78571428571453  84  14  10  0.71428571428670  9   2   2   1.021  531 89  89  1.0120 1   1   1   1.011  454 76  71  0.93421052631690  1   1   1   1.032  39  7   6   0.85714285714341  151 25  14  0.56132 0   0   0   0.0151 43  7   6   0.85714285714343  8   2   1   0.580  7   2   1   0.5141 96  16  16  1.044  67  12  2   0.166666666667right: 509     accuracy:0.883680555556

我的任务就是以label为自变量,绘制出它和train及acc之间的关系。

接到这个任务后,最直观的感受就是常规的洗数据,于是我先把这些数据放在txt文件中存储下来,由于每个数据之间的间隔大于一个空格,我想当然地写个正则匹配脚本将数据间的大空格转换为一个逗号(转换为逗号的目的是这样可以直接转换为CSV表格文件,然而在本次任务中貌似意义不大….)

#**********************Python 3.6.1***************************##*      将txt文本数据中的过长的空格更为一个逗号      *##*****************  Author LQ ******************************##********************** 2018/4/4 ****************************# #!/usr/bin/python# -*- coding: utf-8 -*-import reimport os #os模块与文本操作直接相关的模块#*********下面三句代码作用不详,就是为了防止出现编码问题*********import importlibimport sysimportlib.reload(sys)#****************************************************PATTERN = '\s+'#匹配出文本中的长空格class Cleaner:  #初始化  def __init__(self):    os.chdir('D:\\Learning\\Machine_Learning\\实习\\师姐论文实验') #改变工作目录到txt文件对应的目录    self.content = open("acc-onlyRealImage-Iter2500.txt")    def grab_content(self):    line=self.content.readline()    pre=re.compile(PATTERN)    while line:        line_1=pre.sub(',',line) #将文本的长空格转换为逗号后,利于转成CSV格式,然后label按照升序排列      self.Write_content(line_1)      line = self.content.readline()    def Write_content(self,line_1):    path='acc-onlyRealImage-Iter2500-after.txt'    f=open(path,'a')    f.write('\n'+line_1)   def run(self):     self.grab_content()  if __name__ == '__main__':  cleaner = Cleaner()    cleaner.run()

数据清洗完成后,自然就是绘图了,逛了一些博客后,着手写个脚本,第一版是绘制出label和train及acc的双Y轴折线图,脚本较为简单,就是调用别人造的轮子,直接附上代码:

#**********************Python 3.6.1***************************##*           绘制出双Y轴折线图           *##*****************  Author LQ ******************************##********************** 2018/4/4 ****************************# #!/usr/bin/python# -*- coding: utf-8 -*-import reimport os #os模块与文本操作直接相关的模块import matplotlib.pyplot as pltimport numpy as np#*********下面三句代码作用不详,就是为了防止出现编码问题*********import importlibimport sysimportlib.reload(sys)#****************************************************font2 = {'family' : 'Times New Roman',      'weight' : 'normal',      'size'  : 18,     } class Drawing:  #初始化  def __init__(self):    os.chdir('D:\\Learning\\Machine_Learning\\实习\\师姐论文实验') #改变工作目录到指定文件目录    self.content = open("acc-onlyRealImage-Iter2200-after.txt")    self.content1 = open("acc-onlyRealImage-Iter2500-after.txt")   def grab_content(self):    lines=self.content.readlines()    lines_1=self.content1.readlines()    x_1 = [line.strip().split(',')[0] for line in lines ]#字段以逗号分隔,这里取得是第4列    y_train_1=[line.strip().split(',')[1] for line in lines ]    y_train_2=[line.strip().split(',')[1] for line in lines_1 ]    y_acc_1=[line.strip().split(',')[4] for line in lines ]    y_acc_2=[line.strip().split(',')[4] for line in lines_1 ]    x = list(range(len(x_1)))    y_acc=[]    y_acc1=[]    y_train=[]    y_train1=[]    for i in range(len(y_acc_1)):      y_acc.append(float(y_acc_1[i]))      y_acc1.append(float(y_acc_2[i]))      y_train.append(int(y_train_1[i]))      y_train1.append(int(y_train_2[i]))        #plt.xticks(x, x_1,rotation=0)    fig,left_axis=plt.subplots()         p1, =left_axis.plot(x, y_train,'ro-')    right_axis = left_axis.twinx()     p2, =right_axis.plot(x, y_acc,'bo-')        plt.xticks(x, x_1,rotation=0) #设置x轴的显示形式     #设置左坐标轴以及右坐标轴的范围、精度    left_axis.set_ylim(0,1201)     left_axis.set_yticks(np.arange(0,1201,200))     right_axis.set_ylim(0,1.01)     right_axis.set_yticks(np.arange(0,1.01,0.20))      #设置坐标及标题的大小、颜色    left_axis.set_title('RealAndSimulation-Iter6600',font2)    left_axis.set_xlabel('Labels',font2)    left_axis.set_ylabel('Number of training sets',font2,color='r')    left_axis.tick_params(axis='y', colors='r')     right_axis.set_ylabel('Accuracy',font2,color='b')     right_axis.tick_params(axis='y', colors='b')     plt.show()   def run(self):     self.grab_content() if __name__ == '__main__':  Drawing = Drawing()    Drawing.run()

绘制出的图形如上所示,其实看起来也还不错,不过师姐表示有点乱,建议做个柱形的看看,于是继续撸代码:

#**********************Python 3.6.1***************************##*           绘制单Y轴双变量柱状图          *##*****************  Author LQ ******************************##********************** 2018/4/4 ****************************# #!/usr/bin/python# -*- coding: utf-8 -*-import reimport os #os模块与文本操作直接相关的模块import matplotlib.pyplot as pltimport numpy as np#*********下面三句代码作用不详,就是为了防止出现编码问题*********import importlibimport sysimportlib.reload(sys)#****************************************************font2 = {'family' : 'Times New Roman',  #设置字体     'weight' : 'normal',      'size'  : 18,     } class Drawing:  #初始化  def __init__(self):    os.chdir('D:\\Learning\\Machine_Learning\\实习\\师姐论文实验') #改变工作目录到指定文件的目录    self.content = open("acc-onlyRealImage-Iter2200-after.txt")    self.content1 = open("acc-onlyRealImage-Iter2500-after.txt")    def autolabel(self,rects,y): #在柱状图上面添加 数值    i=0    for rect in rects:      #读出列表存储的value值      value=y[i]       x_1 = rect.get_x() + rect.get_width()/2      y_1 = rect.get_height()      #x_1,y_1对应柱形的横、纵坐标      i+=1      plt.text(x_1, y_1, value, ha='center', va='bottom',fontdict={'size': 8}) #在fontdict中设置字体大小      rect.set_edgecolor('white')   def Pictures(self):    lines=self.content.readlines()    lines_1=self.content1.readlines()    x_1 = [line.strip().split(',')[0] for line in lines ]#字段以逗号分隔,这里取得是第1列    y_train_1=[line.strip().split(',')[1] for line in lines ]    y_train_2=[line.strip().split(',')[1] for line in lines_1 ]    y_acc_1=[line.strip().split(',')[4] for line in lines ]    y_acc_2=[line.strip().split(',')[4] for line in lines_1 ]    x = list(range(len(x_1)))    y_acc=[]    y_acc1=[]    y_train=[]    y_train1=[]    for i in range(len(y_acc_1)):      y_acc.append(float(y_acc_1[i]))      y_acc1.append(float(y_acc_2[i]))      y_train.append(int(y_train_1[i]))      y_train1.append(int(y_train_2[i]))    plt.xticks(x, x_1,rotation=0) #设置X轴坐标值为label值     for i in range(len(x)): #调整柱状图的横坐标,使得打印出来的图形看起来更加舒服       x[i] = x[i] -0.2     a=plt.bar(x, y_train,width=0.4,label='iter2200',fc = 'b')     #a=plt.bar(x, y_acc,width=0.4,label='iter2200',fc = 'b')     for i in range(len(x)):       x[i] = x[i] + 0.4     b=plt.bar(x, y_train1, width=0.4, label='iter2500',fc = 'r')    #b=plt.bar(x, y_acc1, width=0.4, label='iter2500',fc = 'r')    plt.xlabel('Labels',font2)     #设置Y轴值的范围    plt.ylim((0, 1000))    #设置Y轴的刻度值    plt.yticks(np.arange(0,1001, 200))    #plt.ylim((0, 1.1))    #plt.yticks(np.arange(0,1.1, 0.2))     #plt.ylabel('Accuracy',font2)    plt.ylabel('Number of training sets',font2) #字体的格式在font2中有设置    self.autolabel(a,y_train_1) #为柱形图打上数值标签    self.autolabel(b,y_train_2)    #self.autolabel(a,y_acc_1)    #self.autolabel(b,y_acc_2)    #plt.title("RealAndSimulation",font2)    plt.title("OnlyRealImage",font2)    plt.legend()    plt.show()   def run(self):     self.Pictures() if __name__ == '__main__':  Draw = Drawing()    Draw.run()

呈现的效果如下,此处因为对于双柱形图通常采用同一Y轴坐标系,所以此处选择的是比对不同迭代次数:

此处为了方便实验结果的观测,在每个柱形上面均打印出了对应的数值,至此,这部分的任务ending,难度不是很大,不过需要自己耐心编写脚本,调试出好的结果~

以上这篇python绘制双Y轴折线图以及单Y轴双变量柱状图的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    用python建立两个Y轴的XY曲线图方法
    下一条:
    简单了解python的内存管理机制
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客