Python matplotlib讀取excel數(shù)據(jù)并用for循環(huán)畫多個(gè)子圖subplot操作
讀取excel數(shù)據(jù)需要用到xlrd模塊,在命令行運(yùn)行下面命令進(jìn)行安裝
pip install xlrd
表格內(nèi)容大致如下,有若干sheet,每個(gè)sheet記錄了同一所學(xué)校的所有學(xué)生成績,分為語文、數(shù)學(xué)、英語、綜合、總分
| 考號(hào) | 姓名 | 班級(jí) | 學(xué)校 | 語文 | 數(shù)學(xué) | 英語 | 綜合 | 總分 |
| ... | ... | ... | ... | 136 | 136 | 100 | 57 | 429 |
| ... | ... | ... | ... | 128 | 106 | 70 | 54 | 358 |
| ... | ... | ... | ... | 110.5 | 62 | 92 | 44 | 308.5 |
畫多張子圖需要用到subplot函數(shù)
subplot(nrows, ncols, index, **kwargs)
想要在一張畫布上按如下格式畫多張子圖
語文 --- 數(shù)學(xué)
英語 --- 綜合
----- 總分 ----
需要用的subplot參數(shù)分別為
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=[] # 存儲(chǔ)各校名稱--對應(yīng)于excel表格的sheet名
data_index = 0
new_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
'#bcbd22', '#17becf']
wb = owb('raw_data.xlsx') # 數(shù)據(jù)文件
active_districts = ['二小','一小','四小'] ## 填寫需要畫哪些學(xué)校的,名字需要與表格內(nèi)一致
avg_yuwen = []
avg_shuxue = []
avg_yingyu = []
avg_zonghe = []
avg_total = []
'按頁數(shù)依次讀取表格數(shù)據(jù)作為Y軸參數(shù)'
for s in wb.sheets():
#以下兩行用于控制是否全部繪圖,還是只繪選擇的區(qū)
#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
#讀取各科成績并計(jì)算平均分
yuwen = yuwen + (s.cell(row, 4).value - yuwen)/total_student # 語文
shuxue = shuxue + (s.cell(row, 5).value - shuxue) / total_student # 數(shù)學(xué)
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('各校各科成績平均分統(tǒng)計(jì)',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'數(shù)學(xué)')
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()

這樣雖然能畫出來,但是需要手動(dòng)寫每個(gè)subplot的代碼,代碼重復(fù)量太大,能不能用for循環(huán)的方式呢?
繼續(xù)嘗試,
先整理出for循環(huán)需要的不同參數(shù)
avg_scores = [] # 存儲(chǔ)各科成績,2維list subjects = ['語文','數(shù)學(xué)','英語','綜合','總分'] #每個(gè)子圖的title plot_pos = [321,322,323,324,313] # 每個(gè)子圖的位置 y_lims = [(60,130), (50,120), (30,100), (0,60), (200,400)] # 每個(gè)子圖的ylim參數(shù)
數(shù)據(jù)讀取的修改比較簡單,但是到畫圖時(shí),如果還用 ax = plt.subplots(plot_pos[pos])方法的話,會(huì)報(bào)錯(cuò)
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]) 試一試,結(jié)果成功了,整體代碼如下
#!/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=[] # 存儲(chǔ)各校名稱--對應(yīng)于excel表格的sheet名
total_stu=[] # 存儲(chǔ)各區(qū)學(xué)生總數(shù)
data_index = 0
new_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
'#bcbd22', '#17becf']
wb = owb('raw_data.xlsx') # 數(shù)據(jù)文件
active_districts = ['BY','二小','一小','WR','四小'] ## 填寫需要畫哪些學(xué)校的,名字需要與表格內(nèi)一致
avg_scores = [] # 存儲(chǔ)各科成績,2維list
subjects = ['語文','數(shù)學(xué)','英語','綜合','總分'] #每個(gè)子圖的title
plot_pos = [321,322,323,324,313] # 每個(gè)子圖的位置
y_lims = [(60,130), (50,120), (30,100), (0,60), (200,400)] # 每個(gè)子圖的ylim參數(shù)
'按頁數(shù)依次讀取表格數(shù)據(jù)作為Y軸參數(shù)'
for s in wb.sheets():
#以下兩行用于控制是否全部繪圖,還是只繪選擇的區(qū)
#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 # 數(shù)學(xué)
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('各校各科成績平均分統(tǒng)計(jì)',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會(huì)報(bào)錯(cuò)'tuple' object has no attribute 'bar'
y_data = [x[pos] for x in avg_scores] # 按列取數(shù)據(jù)
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()
和之前的結(jié)果一樣,能找到唯一一處細(xì)微差別嘛

以上這篇Python matplotlib讀取excel數(shù)據(jù)并用for循環(huán)畫多個(gè)子圖subplot操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Python數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表詳解
- Python 循環(huán)讀取數(shù)據(jù)內(nèi)存不足的解決方案
- python 使用xlsxwriter循環(huán)向excel中插入數(shù)據(jù)和圖片的操作
- Python 使用xlwt模塊將多行多列數(shù)據(jù)循環(huán)寫入excel文檔的操作
- python 循環(huán)數(shù)據(jù)賦值實(shí)例
- Python中l(wèi)ist循環(huán)遍歷刪除數(shù)據(jù)的正確方法
- Python中循環(huán)后使用list.append()數(shù)據(jù)被覆蓋問題的解決
- python循環(huán)某一特定列的所有行數(shù)據(jù)(方法示例)
相關(guān)文章
python中import,from……import的使用詳解
這篇文章主要介紹了python中import,from……import的使用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
Pytorch+PyG實(shí)現(xiàn)GraphSAGE過程示例詳解
這篇文章主要為大家介紹了Pytorch+PyG實(shí)現(xiàn)GraphSAGE過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
用Django實(shí)現(xiàn)一個(gè)可運(yùn)行的區(qū)塊鏈應(yīng)用
這篇文章主要介紹了用Django實(shí)現(xiàn)一個(gè)可運(yùn)行的區(qū)塊鏈應(yīng)用,需要的朋友可以參考下2018-03-03
python 計(jì)算積分圖和haar特征的實(shí)例代碼
今天小編就為大家分享一篇python 計(jì)算積分圖和haar特征的實(shí)例代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

