1. 程式人生 > 程式設計 >Python matplotlib讀取excel資料並用for迴圈畫多個子圖subplot操作

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 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,len(avg_shuxue)):
 ax2.text(my_x[i],avg_shuxue[i],'%.2f' %(avg_shuxue[i]),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,len(avg_yingyu)):
 ax3.text(my_x[i],avg_yingyu[i],'%.2f' % (avg_yingyu[i]),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,len(avg_zonghe)):
 ax4.text(my_x[i],avg_zonghe[i],'%.2f' % (avg_zonghe[i]),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,len(avg_total)):
 ax5.text(my_x[i],avg_total[i],'%.2f' % (avg_total[i]),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,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,FuncFormatter
import numpy as np
 
districts=[] # 儲存各校名稱--對應於excel表格的sheet名
total_stu=[] # 儲存各區學生總數
data_index = 0
new_colors = ['#1f77b4','#17becf']
wb = owb('raw_data.xlsx') # 資料檔案
active_districts = ['BY','二小','WR','四小'] ## 填寫需要畫哪些學校的,名字需要與表格內一致
avg_scores = [] # 儲存各科成績,2維list
subjects = ['語文',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,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,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,color=new_colors) # 畫柱狀圖
 for i in np.arange(len(y_data)):
  ax.text(my_x[i],y_data[i],'%.2f' % (y_data[i]),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操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。