Python matplotlib讀取excel數據并用for循環畫多個子圖subplot操作
讀取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 owbimport matplotlib.pyplot as plt#import matplotlib.colors as colors#from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatterimport numpy as np districts=[] # 存儲各校名稱--對應于excel表格的sheet名data_index = 0new_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,14fig = 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()
這樣雖然能畫出來,但是需要手動寫每個subplot的代碼,代碼重復量太大,能不能用for循環的方式呢?
繼續嘗試,
先整理出for循環需要的不同參數
avg_scores = [] # 存儲各科成績,2維listsubjects = [’語文’,’數學’,’英語’,’綜合’,’總分’] #每個子圖的titleplot_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 owbimport matplotlib.pyplot as plt#import matplotlib.colors as colors#from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatterimport numpy as np districts=[] # 存儲各校名稱--對應于excel表格的sheet名total_stu=[] # 存儲各區學生總數data_index = 0new_colors = [’#1f77b4’, ’#ff7f0e’, ’#2ca02c’, ’#d62728’, ’#9467bd’, ’#8c564b’, ’#e377c2’, ’#7f7f7f’, ’#bcbd22’, ’#17becf’]wb = owb(’raw_data.xlsx’) # 數據文件active_districts = [’BY’,’二小’,’一小’,’WR’,’四小’] ## 填寫需要畫哪些學校的,名字需要與表格內一致avg_scores = [] # 存儲各科成績,2維listsubjects = [’語文’,’數學’,’英語’,’綜合’,’總分’] #每個子圖的titleplot_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’]=Falsefigsize = 11,14fig = 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操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: