博客
关于我
读取excel文件并使用matplotlib绘图(含柱状图、柱状图加数值的显示和直方图)
阅读量:538 次
发布时间:2019-03-08

本文共 3628 字,大约阅读时间需要 12 分钟。

  • 首先推荐matplotlib官网的各种显示代码实例(包括3D图的绘制):

  • 其次推荐matplotlib官网教程:

  • xlrd官网api(Excel操作):

1. 读取excel数据,并显示折线图

代码如下

#!/usr/bin/env python'''测试环境:ubuntu18.04下测试'''import numpy as npimport matplotlib.pyplot as pltimport xlrd# 打开一个workbookworkbook = xlrd.open_workbook('/home/myName/python_ws/excel_matplot_ws/read_plot/plot_data.xlsx')# window下要加r# 抓取所有sheet页的名称worksheets = workbook.sheet_names()#Sheet1,Sheet2...print('worksheets is %s' % worksheets)#我的sheetmySheet = workbook.sheet_by_name(u'Sheet1')# table = excel_file.sheet_by_index(1) # 通过索引打开'''1. 整行或者整列:myData = mySheet.row_values(0). # 0整行。col_values(0)表示0整列2.  (1)单元格取值:mySheet.cell_value(1,1)取1行1列格子的值,从0开始。     (2)单元格取值:mySheet.row(2)[3].value # 第3行第4列的值     (3)单元格取值:mySheet.cell(0,1).value3. 行数、列数:mySheet.nrows和mySheet.ncols'''myData1 = []myData2 = []myData3 = []myData4 = []myData5 = []for c in range(1,8):    myData1.append(mySheet.cell(1, c).value)for c in range(1,8):    myData2.append(mySheet.cell(2, c).value)for c in range(1,8):    myData3.append(mySheet.cell(3, c).value)for c in range(1,8):    myData4.append(mySheet.cell(4, c).value)for c in range(1,8):    myData5.append(mySheet.cell(5, c).value)print(myData2)x = range(0,7)plt.title("测试结果")plt.ylabel("数值大小:ms")plt.xlabel("数值类型")l1, = plt.plot(x, myData1)# 默认折线、实线l2, = plt.plot(x, myData2, color="blue", linewidth=1.5, linestyle="-") # 蓝色,1.5宽,线段l3, = plt.plot(x, myData3,'r',linewidth = 2.5,linestyle ='--')# 红色,2.5宽,虚线l4, = plt.plot(x, myData4,'c',linestyle ='-.')# 线段类型-.l5, = plt.plot(x, myData5,linestyle =':')# 虚点plt.legend(handles=[l1,l2, l3, l4, l5],labels=['PoseOptimization','OptimizeSim3','LocalBundleAdjustment', 'OptimizeEssentialGraph', 'GlobalBundleAdjustment'],loc='best')# plt.xlim((0,4))    # 坐标轴的取值范围# plt.ylim((1,10))plt.show()

测试结果:

在这里插入图片描述
测试数据为:
在这里插入图片描述

2. 柱状图或条形图

import numpy as npimport matplotlib.pyplot as pltx1 =[1,3,,7,9]x2 =[2,4,6,8,10]y1=[15,3,3,3,20]y2 =[6,12,22,15,12]plt.bar(x1,y1,label='bar1')plt.bar(x2,y2,label='bar2')plt.xlabel('x轴')plt.ylabel('y轴')plt.title('柱形图')plt.legend()plt.show()

在这里插入图片描述

3. 柱状图加数值

mport numpy as npimport matplotlib.pyplot as pltdef auto_label(rects):    for rect in rects:        height = rect.get_height()        ax.annotate('{}'.format(height), # put the detail data                    xy=(rect.get_x() + rect.get_width() / 2, height), # get the center location.                    xytext=(0, 3),  # 3 points vertical offset                    textcoords="offset points",                    ha='center', va='bottom')                    def auto_text(rects):    for rect in rects:        ax.text(rect.get_x(), rect.get_height(), rect.get_height(), ha='left', va='bottom')        labels = ['L1', 'L2', 'L3', 'L4', 'L5']men_means = [20, 34, 30, 35, 27]women_means = [25, 32, 34, 20, 25]index = np.arange(len(labels))width = 0.2fig, ax = plt.subplots()#和上例子一样,添加数据,并添加角标rect1 = ax.bar(index - width / 2, men_means, color ='lightcoral', width=width, label ='Men')rect2 = ax.bar(index + width / 2, women_means, color ='springgreen', width=width, label ='Women')ax.set_title('按性别统计分数')ax.set_xticks(ticks=index)ax.set_xticklabels(labels)ax.set_ylabel('分数')ax.set_ylim(0, 50)# auto_label(rect1)# auto_label(rect2)auto_text(rect1)auto_text(rect2)ax.legend(loc='upper right', frameon=False)fig.tight_layout()#plt.savefig('2.tif', dpi=300)# 保存图片plt.show()

输出结果:

在这里插入图片描述

4. 直方图

直方图属于一种统计类型,下面的例子表示统计年龄段内人数。

population_ages =[22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]bins= [0,10,20,30,40,50,60,70,80,90,100,110,120,130]# 分组plt.hist(population_ages,bins,label='直方图')plt.xlabel('x轴')plt.ylabel('y轴')plt.title('直方图')plt.legend()plt.show()

输出结果:

在这里插入图片描述

转载地址:http://fkbiz.baihongyu.com/

你可能感兴趣的文章
MySQL - 解读MySQL事务与锁机制
查看>>
MTTR、MTBF、MTTF的大白话理解
查看>>
mt_rand
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>