Python matplotlib讀取excel數(shù)據并用for循環(huán)畫多個子圖subplot操作
讀取excel數(shù)據需要用到xlrd模塊,在命令行運行下面命令進行安裝
pip install xlrd
表格內容大致如下,有若干sheet,每個sheet記錄了同一所學校的所有學生成績,分為語文、數(shù)學、英語、綜合、總分
| 考號 | 姓名 | 班級 | 學校 | 語文 | 數(shù)學 | 英語 | 綜合 | 總分 |
| ... | ... | ... | ... | 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ù)學
英語 --- 綜合
----- 總分 ----
需要用的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=[] # 存儲各校名稱--對應于excel表格的sheet名
data_index = 0
new_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
'#bcbd22', '#17becf']
wb = owb('raw_data.xlsx') # 數(shù)據文件
active_districts = ['二小','一小','四小'] ## 填寫需要畫哪些學校的,名字需要與表格內一致
avg_yuwen = []
avg_shuxue = []
avg_yingyu = []
avg_zonghe = []
avg_total = []
'按頁數(shù)依次讀取表格數(shù)據作為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
#讀取各科成績并計算平均分
yuwen = yuwen + (s.cell(row, 4).value - yuwen)/total_student # 語文
shuxue = shuxue + (s.cell(row, 5).value - shuxue) / total_student # 數(shù)學
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)計',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ù)學')
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()

這樣雖然能畫出來,但是需要手動寫每個subplot的代碼,代碼重復量太大,能不能用for循環(huán)的方式呢?
繼續(xù)嘗試,
先整理出for循環(huán)需要的不同參數(shù)
avg_scores = [] # 存儲各科成績,2維list subjects = ['語文','數(shù)學','英語','綜合','總分'] #每個子圖的title plot_pos = [321,322,323,324,313] # 每個子圖的位置 y_lims = [(60,130), (50,120), (30,100), (0,60), (200,400)] # 每個子圖的ylim參數(shù)
數(shù)據讀取的修改比較簡單,但是到畫圖時,如果還用 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=[] # 存儲各區(qū)學生總數(shù)
data_index = 0
new_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
'#bcbd22', '#17becf']
wb = owb('raw_data.xlsx') # 數(shù)據文件
active_districts = ['BY','二小','一小','WR','四小'] ## 填寫需要畫哪些學校的,名字需要與表格內一致
avg_scores = [] # 存儲各科成績,2維list
subjects = ['語文','數(shù)學','英語','綜合','總分'] #每個子圖的title
plot_pos = [321,322,323,324,313] # 每個子圖的位置
y_lims = [(60,130), (50,120), (30,100), (0,60), (200,400)] # 每個子圖的ylim參數(shù)
'按頁數(shù)依次讀取表格數(shù)據作為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ù)學
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)計',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] # 按列取數(shù)據
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數(shù)據并用for循環(huán)畫多個子圖subplot操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Python數(shù)據結構之循環(huán)鏈表詳解
- Python 循環(huán)讀取數(shù)據內存不足的解決方案
- python 使用xlsxwriter循環(huán)向excel中插入數(shù)據和圖片的操作
- Python 使用xlwt模塊將多行多列數(shù)據循環(huán)寫入excel文檔的操作
- python 循環(huán)數(shù)據賦值實例
- Python中l(wèi)ist循環(huán)遍歷刪除數(shù)據的正確方法
- Python中循環(huán)后使用list.append()數(shù)據被覆蓋問題的解決
- python循環(huán)某一特定列的所有行數(shù)據(方法示例)
相關文章
python實現(xiàn)批量監(jiān)聽頁面并發(fā)送郵件
這篇文章主要為大家詳細介紹了python如何實現(xiàn)自動化批量監(jiān)聽頁面并發(fā)送郵件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-11-11
python dataframe astype 字段類型轉換方法
下面小編就為大家分享一篇python dataframe astype 字段類型轉換方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python流程控制 while循環(huán)實現(xiàn)解析
這篇文章主要介紹了Python流程控制 while循環(huán)實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09

