Python matplotlib读取excel数据并用for循环画多个子图subplot操作


Posted in Python onJuly 14, 2020

读取excel数据需要用到xlrd模块,在命令行运行下面命令进行安装

pip install xlrd

表格内容大致如下,有若干sheet,每个sheet记录了同一所学校的所有学生成绩,分为语文、数学、英语、综合、总分

考号 姓名 班级 学校 语文 数学 英语 综合 总分
... ... ... ... 136 136 100 57 429
... ... ... ... 128 106 70 54 358
... ... ... ... 110.5 62 92 44 308.5

画多张子图需要用到subplot函数

subplot(nrows, ncols, index, **kwargs)

想要在一张画布上按如下格式画多张子图

语文 --- 数学

英语 --- 综合

----- 总分 ----

需要用的subplot参数分别为

subplot(321) --- subplot(322)

subplot(323) --- subplot(324)

subplot(313)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from xlrd import open_workbook as owb
import matplotlib.pyplot as plt
#import matplotlib.colors as colors
#from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatter
import numpy as np
 
districts=[] # 存储各校名称--对应于excel表格的sheet名
data_index = 0
new_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
    '#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
    '#bcbd22', '#17becf']
wb = owb('raw_data.xlsx') # 数据文件
active_districts = ['二小','一小','四小'] ## 填写需要画哪些学校的,名字需要与表格内一致
avg_yuwen = []
avg_shuxue = []
avg_yingyu = []
avg_zonghe = []
avg_total = []
'按页数依次读取表格数据作为Y轴参数'
for s in wb.sheets():
 #以下两行用于控制是否全部绘图,还是只绘选择的区
 #if s.name not in active_districts:
  # continue
 print('Sheet: ', s.name)
 districts.append(s.name)
 avg_score = 0
 yuwen = 0
 shuxue = 0
 yingyu = 0
 zonghe = 0
 zongfen = 0
 total_student = 0
 for row in range(1,s.nrows):
  total_student += 1
  #读取各科成绩并计算平均分
  yuwen = yuwen + (s.cell(row, 4).value - yuwen)/total_student # 语文
  shuxue = shuxue + (s.cell(row, 5).value - shuxue) / total_student # 数学
  yingyu = yingyu + (s.cell(row, 6).value - yingyu) / total_student # 英语
  zonghe = zonghe + (s.cell(row, 7).value - zonghe) / total_student # 综合
  zongfen = zongfen + (s.cell(row, 8).value - zongfen) / total_student # 总分
 avg_yuwen.append(yuwen)
 avg_shuxue.append(shuxue)
 avg_yingyu.append(yingyu)
 avg_zonghe.append(zonghe)
 avg_total.append(zongfen)
 data_index += 1
 
print('开始画图...')
plt.rcParams['font.sans-serif']=['SimHei'] # 中文支持
plt.rcParams['axes.unicode_minus']=False # 中文支持
figsize = 11,14
fig = plt.figure(figsize=figsize)
fig.suptitle('各校各科成绩平均分统计',fontsize=18)
my_x=np.arange(len(districts))
width=0.5
 
ax1 = plt.subplot(321)
#total_width=width*(len(districts))
b = ax1.bar(my_x , avg_yuwen, width, tick_label=districts, align='center', color=new_colors)
for i in range(0,len(avg_yuwen)):
 ax1.text(my_x[i], avg_yuwen[i], '%.2f' % (avg_yuwen[i]), ha='center', va='bottom',fontsize=10)
ax1.set_title(u'语文')
ax1.set_ylabel(u"平均分")
ax1.set_ylim(60, 130)
 
ax2 = plt.subplot(322)
ax2.bar(my_x, avg_shuxue, width, tick_label=districts, align='center', color=new_colors)
for i in range(0, len(avg_shuxue)):
 ax2.text(my_x[i], avg_shuxue[i], '%.2f' %(avg_shuxue[i]), ha='center', va='bottom', fontsize=10)
ax2.set_title(u'数学')
ax2.set_ylabel(u'平均分')
ax2.set_ylim(50,120)
 
ax3 = plt.subplot(323)
b = ax3.bar(my_x , avg_yingyu, width, tick_label=districts, align='center', color=new_colors)
for i in range(0,len(avg_yingyu)):
 ax3.text(my_x[i], avg_yingyu[i], '%.2f' % (avg_yingyu[i]), ha='center', va='bottom',fontsize=10)
ax3.set_title(u'英语')
ax3.set_ylabel(u"平均分")
ax3.set_ylim(30, 100)
 
ax4 = plt.subplot(324)
b = ax4.bar(my_x , avg_zonghe, width, tick_label=districts, align='center', color=new_colors)
for i in range(0,len(avg_zonghe)):
 ax4.text(my_x[i], avg_zonghe[i], '%.2f' % (avg_zonghe[i]), ha='center', va='bottom',fontsize=10)
ax4.set_title(u'综合')
ax4.set_ylabel(u"平均分")
ax4.set_ylim(0, 60)
 
ax5 = plt.subplot(313)
total_width=width*(len(districts))
b = ax5.bar(my_x , avg_total, width, tick_label=districts, align='center', color=new_colors)
for i in range(0,len(avg_total)):
 ax5.text(my_x[i], avg_total[i], '%.2f' % (avg_total[i]), ha='center', va='bottom',fontsize=10)
ax5.set_title(u'总分')
ax5.set_ylabel(u"平均分")
ax5.set_ylim(250, 400)
 
plt.savefig('avg.png')
plt.show()

Python matplotlib读取excel数据并用for循环画多个子图subplot操作

这样虽然能画出来,但是需要手动写每个subplot的代码,代码重复量太大,能不能用for循环的方式呢?

继续尝试,

先整理出for循环需要的不同参数

avg_scores = [] # 存储各科成绩,2维list
subjects = ['语文','数学','英语','综合','总分'] #每个子图的title
plot_pos = [321,322,323,324,313] # 每个子图的位置
y_lims = [(60,130), (50,120), (30,100), (0,60), (200,400)] # 每个子图的ylim参数

数据读取的修改比较简单,但是到画图时,如果还用 ax = plt.subplots(plot_pos[pos])方法的话,会报错

Traceback (most recent call last):
 File "...xxx.py", line 66, in <module>
 b = ax.bar(my_x , y_data, width, tick_label=districts, align='center', color=new_colors) # 画柱状图
AttributeError: 'tuple' object has no attribute 'bar'

搜索一番,没找到合适的答案,想到可以换fig.add_subplot(plot_pos[pos]) 试一试,结果成功了,整体代码如下

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from xlrd import open_workbook as owb
import matplotlib.pyplot as plt
#import matplotlib.colors as colors
#from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatter
import numpy as np
 
districts=[] # 存储各校名称--对应于excel表格的sheet名
total_stu=[] # 存储各区学生总数
data_index = 0
new_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
    '#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
    '#bcbd22', '#17becf']
wb = owb('raw_data.xlsx') # 数据文件
active_districts = ['BY','二小','一小','WR','四小'] ## 填写需要画哪些学校的,名字需要与表格内一致
avg_scores = [] # 存储各科成绩,2维list
subjects = ['语文','数学','英语','综合','总分'] #每个子图的title
plot_pos = [321,322,323,324,313] # 每个子图的位置
y_lims = [(60,130), (50,120), (30,100), (0,60), (200,400)] # 每个子图的ylim参数
 
'按页数依次读取表格数据作为Y轴参数'
for s in wb.sheets():
 #以下两行用于控制是否全部绘图,还是只绘选择的区
 #if s.name not in active_districts:
  # continue
 print('Sheet: ', s.name)
 districts.append(s.name)
 avg_scores.append([])
 yuwen = 0
 shuxue = 0
 yingyu = 0
 zonghe = 0
 zongfen = 0
 total_student = 0
 for row in range(1,s.nrows):
  total_student += 1
  #tmp = s.cell(row,4).value
  yuwen = yuwen + (s.cell(row, 4).value - yuwen)/total_student # 语文
  shuxue = shuxue + (s.cell(row, 5).value - shuxue) / total_student # 数学
  yingyu = yingyu + (s.cell(row, 6).value - yingyu) / total_student # 英语
  zonghe = zonghe + (s.cell(row, 7).value - zonghe) / total_student # 综合
  zongfen = zongfen + (s.cell(row, 8).value - zongfen) / total_student # 总分
 avg_scores[data_index].append(yuwen)
 avg_scores[data_index].append(shuxue)
 avg_scores[data_index].append(yingyu)
 avg_scores[data_index].append(zonghe)
 avg_scores[data_index].append(zongfen)
 data_index += 1
 
print('开始画图...')
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
figsize = 11,14
fig = plt.figure(figsize=figsize)
fig.suptitle('各校各科成绩平均分统计',fontsize=18)
my_x=np.arange(len(districts))
width=0.5
 
print(avg_scores)
for pos in np.arange(len(plot_pos)):
 #ax = plt.subplots(plot_pos[pos])
 ax = fig.add_subplot(plot_pos[pos]) # 如果用ax = plt.subplots会报错'tuple' object has no attribute 'bar'
 y_data = [x[pos] for x in avg_scores] # 按列取数据
 print(y_data)
 b = ax.bar(my_x , y_data, width, tick_label=districts, align='center', color=new_colors) # 画柱状图
 for i in np.arange(len(y_data)):
  ax.text(my_x[i], y_data[i], '%.2f' % (y_data[i]), ha='center', va='bottom',fontsize=10) # 添加文字
 ax.set_title(subjects[pos])
 ax.set_ylabel(u"平均分")
 ax.set_ylim(y_lims[pos])
 
plt.savefig('jh_avg_auto.png')
plt.show()

和之前的结果一样,能找到唯一一处细微差别嘛

Python matplotlib读取excel数据并用for循环画多个子图subplot操作

以上这篇Python matplotlib读取excel数据并用for循环画多个子图subplot操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python下线程之间的共享和释放示例
May 04 Python
python使用线程封装的一个简单定时器类实例
May 16 Python
Python更新数据库脚本两种方法及对比介绍
Jul 27 Python
Selenium chrome配置代理Python版的方法
Nov 29 Python
解决新版Pycharm中Matplotlib图像不在弹出独立的显示窗口问题
Jan 15 Python
使用Template格式化Python字符串的方法
Jan 22 Python
opencv设置采集视频分辨率方式
Dec 10 Python
keras tensorflow 实现在python下多进程运行
Feb 06 Python
Python基于requests库爬取网站信息
Mar 02 Python
python如何绘制疫情图
Sep 16 Python
python requests模块的使用示例
Apr 07 Python
在Python 中将类对象序列化为JSON
Apr 06 Python
python3 循环读取excel文件并写入json操作
Jul 14 #Python
Python爬虫实例——scrapy框架爬取拉勾网招聘信息
Jul 14 #Python
Python爬虫爬取新闻资讯案例详解
Jul 14 #Python
Win10下配置tensorflow-gpu的详细教程(无VS2015/2017)
Jul 14 #Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
Jul 14 #Python
python操作微信自动发消息的实现(微信聊天机器人)
Jul 14 #Python
python如何写try语句
Jul 14 #Python
You might like
10个实用的PHP代码片段
2011/09/02 PHP
PHP的SQL注入过程分析
2012/01/06 PHP
php array_walk_recursive 使用自定的函数处理数组中的每一个元素
2016/11/16 PHP
JavaScript对表格或元素按文本,数字或日期排序的方法
2015/05/26 Javascript
JQuery给网页更换皮肤的方法
2015/05/30 Javascript
js+html5操作sqlite数据库的方法
2016/02/02 Javascript
WordPress 单页面上一页下一页的实现方法【附代码】
2016/03/10 Javascript
如何使用AngularJs打造权限管理系统【简易型】
2016/05/09 Javascript
js定义类的几种方法(推荐)
2016/06/08 Javascript
jQuery中checkbox反复调用attr('checked', true/false)只有第一次生效的解决方法
2016/11/16 Javascript
jQuery模拟窗口抖动效果
2017/03/15 Javascript
Angular.js中ng-include用法及多标签页面的实现方式详解
2017/05/07 Javascript
5分钟打造简易高效的webpack常用配置
2017/07/04 Javascript
JSON 数据格式详解
2017/09/13 Javascript
vue2.0+ 从插件开发到npm发布的示例代码
2018/04/28 Javascript
微信小程序扫描二维码获取信息实例详解
2019/05/07 Javascript
vue+echarts+datav大屏数据展示及实现中国地图省市县下钻功能
2020/11/16 Javascript
[02:23]2014DOTA2国际邀请赛中国战队回顾
2014/08/01 DOTA
讲解Python中的递归函数
2015/04/27 Python
Python实现接受任意个数参数的函数方法
2018/04/21 Python
Python爬虫将爬取的图片写入world文档的方法
2018/11/07 Python
Python+PyQT5的子线程更新UI界面的实例
2019/06/14 Python
python读取ini配置文件过程示范
2019/12/23 Python
django的autoreload机制实现
2020/06/03 Python
CSS3制作漂亮的照片墙的实现代码
2016/06/08 HTML / CSS
HTML5自定义属性前缀data-及dataset的使用方法(html5 新特性)
2017/08/24 HTML / CSS
全球速卖通法国在线交易平台:AliExpress法国
2017/07/07 全球购物
美国市场上最实惠的送餐服务:Dinnerly
2018/03/18 全球购物
公司外出活动方案
2014/08/14 职场文书
学校周年庆活动方案
2014/08/22 职场文书
搞笑老公保证书
2015/02/26 职场文书
银行资信证明
2015/06/17 职场文书
纯CSS实现酷炫的霓虹灯效果
2021/04/13 HTML / CSS
浅谈resultMap的用法及关联结果集映射
2021/06/30 Java/Android
深入浅析Django MTV模式
2021/09/04 Python
MySQL基于索引的压力测试的实现
2021/11/07 MySQL