Python從Excel讀取數(shù)據(jù)并使用Matplotlib繪制成二維圖像
知識點(diǎn)
- 使用 xlrd 擴(kuò)展包讀取 Excel 數(shù)據(jù)
- 使用 Matplotlib 繪制二維圖像
- 顯示 LaTeX 風(fēng)格公式
- 坐標(biāo)點(diǎn)處透明化
接下來,我們將通過實(shí)踐操作,帶領(lǐng)大家使用 Python 實(shí)現(xiàn)從 Excel 讀取數(shù)據(jù)繪制成精美圖像。
首先,我們來繪制一個非常簡單的正弦函數(shù),代碼如下:
import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = np.linspace(0, 10, 500) dashes = [10, 5, 100, 5] # 10 points on, 5 off, 100 on, 5 off fig, ax = plt.subplots() line1, = ax.plot(x, np.sin(x), '--', linewidth=2, label='Dashes set retroactively') line1.set_dashes(dashes) line2, = ax.plot(x, -1 * np.sin(x), dashes=[30, 5, 10, 5], label='Dashes set proactively') ax.legend(loc='lower right')
測試 xlrd 擴(kuò)展包
xlrd 顧名思義,就是 Excel 文件的后綴名 .xl
文件 read
的擴(kuò)展包。這個包只能讀取文件,不能寫入。寫入需要使用另外一個包。但是這個包,其實(shí)也能讀取.xlsx
文件。
從 Excel 中讀取數(shù)據(jù)的過程比較簡單,首先從 xlrd 包導(dǎo)入 open_workbook
,然后打開 Excel 文件,把每個 sheet
里的每一行每一列數(shù)據(jù)都讀取出來即可。很明顯,這是個循環(huán)過程。
## 下載所需示例數(shù)據(jù) ## 1. https://labfile.oss.aliyuncs.com/courses/791/my_data.xlsx ## 2. https://labfile.oss.aliyuncs.com/courses/791/phase_detector.xlsx ## 3. https://labfile.oss.aliyuncs.com/courses/791/phase_detector2.xlsx from xlrd import open_workbook x_data1 = [] y_data1 = [] wb = open_workbook('phase_detector.xlsx') for s in wb.sheets(): print('Sheet:', s.name) for row in range(s.nrows): print('the row is:', row) values = [] for col in range(s.ncols): values.append(s.cell(row, col).value) print(values) x_data1.append(values[0]) y_data1.append(values[1])
如果安裝包沒有問題,這段代碼應(yīng)該能打印出 Excel 表中的數(shù)據(jù)內(nèi)容。解釋一下這段代碼:
- 打開一個 Excel 文件后,首先對文件內(nèi)的
sheet
進(jìn)行循環(huán),這是最外層循環(huán)。 - 在每個
sheet
內(nèi),進(jìn)行第二次循環(huán),行循環(huán)。 - 在每行內(nèi),進(jìn)行列循環(huán),這是第三層循環(huán)。
在最內(nèi)層列循環(huán)內(nèi),取出行列值,復(fù)制到新建的 values
列表內(nèi),很明顯,源數(shù)據(jù)有幾列,values
列表就有幾個元素。我們例子中的 Excel 文件有兩列,分別對應(yīng)角度和 DC 值。所以在列循環(huán)結(jié)束后,我們將取得的數(shù)據(jù)保存到 x_data1
和 y_data1
這兩個列表中。
繪制圖像 V1
第一個版本的功能很簡單,從 Excel 中讀取數(shù)據(jù),然后繪制成圖像。同樣先下載所需數(shù)據(jù):
def read_xlsx(name): wb = open_workbook(name) x_data = [] y_data = [] for s in wb.sheets(): for row in range(s.nrows): values = [] for col in range(s.ncols): values.append(s.cell(row, col).value) x_data.append(values[0]) y_data.append(values[1]) return x_data, y_data x_data, y_data = read_xlsx('my_data.xlsx') plt.plot(x_data, y_data, 'bo-', label=u"Phase curve", linewidth=1) plt.title(u"TR14 phase detector") plt.legend() plt.xlabel(u"input-deg") plt.ylabel(u"output-V")
從 Excel 中讀取數(shù)據(jù)的程序,上面已經(jīng)解釋過了。這段代碼后面的函數(shù)是 Matplotlib 繪圖的基本格式,此處的輸入格式為:plt.plot(x 軸數(shù)據(jù), y 軸數(shù)據(jù), 曲線類型, 圖例說明, 曲線線寬)
。圖片頂部的名稱,由 plt.title(u"TR14 phase detector")
語句定義。最后,使用 plt.legend()
使能顯示圖例。
繪制圖像 V2
這個圖只繪制了一個表格的數(shù)據(jù),我們一共有三個表格。但是就這個一個已經(jīng)夠丑了,我們先來美化一下。首先,坐標(biāo)軸的問題:橫軸的 0 點(diǎn)對應(yīng)著縱軸的 8,這個明顯不行。我們來移動一下坐標(biāo)軸,使之 0 點(diǎn)重合:
from pylab import gca plt.plot(x_data, y_data, 'bo-', label=u"Phase curve", linewidth=1) plt.title(u"TR14 phase detector") plt.legend() ax = gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xlabel(u"input-deg") plt.ylabel(u"output-V")
好的,移動坐標(biāo)軸后,圖片稍微順眼了一點(diǎn),我們也能明顯的看出來,圖像與橫軸的交點(diǎn)大約在 180 度附近。
解釋一下移動坐標(biāo)軸的代碼:我們要移動坐標(biāo)軸,首先要把舊的坐標(biāo)拆了。怎么拆呢?原圖是上下左右四面都有邊界刻度的圖像,我們首先把右邊界拆了不要了,使用語句 ax.spines['right'].set_color('none')
。
把右邊界的顏色設(shè)置為不可見,右邊界就拆掉了。同理,再把上邊界拆掉 ax.spines['top'].set_color('none')
。
拆完之后,就只剩下我們關(guān)心的左邊界和下邊界了,這倆就是 x
軸和 y
軸。然后我們移動這兩個軸,使他們的零點(diǎn)對應(yīng)起來:
ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0))
這樣,就完成了坐標(biāo)軸的移動。
繪制圖像 V3
我們能不能給圖像過零點(diǎn)加個標(biāo)記呢?顯示的告訴看圖者,過零點(diǎn)在哪,就免去看完圖還得猜,要么就要問作報告的人。
plt.plot(x_data, y_data, 'bo-', label=u"Phase curve", linewidth=1) plt.annotate('zero point', xy=(180, 0), xytext=(60, 3), arrowprops=dict(facecolor='black', shrink=0.05),) plt.title(u"TR14 phase detector") plt.legend() ax = gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xlabel(u"input-deg") plt.ylabel(u"output-V")
好的,加上標(biāo)注的圖片,顯示效果更好了。標(biāo)注的添加,使用 plt.annotate(標(biāo)注文字, 標(biāo)注的數(shù)據(jù)點(diǎn), 標(biāo)注文字坐標(biāo), 箭頭形狀) 語句。這其中,標(biāo)注的數(shù)據(jù)點(diǎn)是我們感興趣的,需要說明的數(shù)據(jù),而標(biāo)注文字坐標(biāo),需要我們根據(jù)效果進(jìn)行調(diào)節(jié),既不能遮擋原曲線,又要醒目。
繪制圖像 V4
我們把三組數(shù)據(jù)都畫在這幅圖上,方便對比,此外,再加上一組理想數(shù)據(jù)進(jìn)行對照。這一次我們再做些改進(jìn),把橫坐標(biāo)的單位用 LaTeX 引擎顯示;不光標(biāo)記零點(diǎn),把兩邊的非線性區(qū)也標(biāo)記出來;
plt.annotate('Close loop point', size=18, xy=(180, 0.1), xycoords='data', xytext=(-100, 40), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2") ) plt.annotate(' ', xy=(0, -0.1), xycoords='data', xytext=(200, -90), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-.2") ) plt.annotate('Zero point in non-monotonic region', size=18, xy=(360, 0), xycoords='data', xytext=(-290, -110), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2") ) plt.plot(x_data, y_data, 'b', label=u"Faster D latch and XOR", linewidth=2) x_data1, y_data1 = read_xlsx('phase_detector.xlsx') plt.plot(x_data1, y_data1, 'g', label=u"Original", linewidth=2) x_data2, y_data2 = read_xlsx('phase_detector2.xlsx') plt.plot(x_data2, y_data2, 'r', label=u"Move the pullup resistor", linewidth=2) x_data3 = [] y_data3 = [] for i in range(360): x_data3.append(i) y_data3.append((i-180)*0.052-0.092) plt.plot(x_data3, y_data3, 'c', label=u"The Ideal Curve", linewidth=2) plt.title(u"$2\pi$ phase detector", size=20) plt.legend(loc=0) # 顯示 label # 移動坐標(biāo)軸代碼 ax = gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xlabel(u"$\phi/deg$", size=20) plt.ylabel(u"$DC/V$", size=20)
LaTeX 表示數(shù)學(xué)公式,使用 $$
表示兩個符號之間的內(nèi)容是數(shù)學(xué)符號。圓周率就可以簡單表示為 $\pi$
,簡單到哭,顯示效果卻很好看。同樣的,$\phi$
表示角度符號,書寫和讀音相近,很好記。
對于圓周率,角度公式這類數(shù)學(xué)符號,使用 LaTeX 來表示,是非常方便的。這張圖比起上面的要好看得多了。但是,依然覺得還是有些丑。好像用平滑線畫出來的圖像,并不如用點(diǎn)線畫出來的好看。而且點(diǎn)線更能反映實(shí)際的數(shù)據(jù)點(diǎn)。此外,我們的圖像跟坐標(biāo)軸重疊的地方,把坐標(biāo)和數(shù)字都擋住了,看著不太美。
圖中的理想曲線的數(shù)據(jù),是根據(jù)電路原理純計算出來的,要講清楚需要較大篇幅,這里就不展開了,只是為了配合比較而用,這部分代碼,大家知道即可:
for i in range(360): x_data3.append(i) y_data3.append((i-180)*0.052-0.092) plt.plot(x_data3, y_data3, 'c', label=u"The Ideal Curve", linewidth=2)
繪制圖像 V5
我們再就上述問題,進(jìn)行優(yōu)化。優(yōu)化的過程包括:改變橫坐標(biāo)的顯示,使用弧度顯示;優(yōu)化圖像與橫坐標(biāo)相交的部分,透明顯示;增加網(wǎng)絡(luò)標(biāo)度。
plt.annotate('The favorite close loop point', size=16, xy=(1, 0.1), xycoords='data', xytext=(-180, 40), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2") ) plt.annotate(' ', xy=(0.02, -0.2), xycoords='data', xytext=(200, -90), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-.2") ) plt.annotate('Zero point in non-monotonic region', size=16, xy=(1.97, -0.3), xycoords='data', xytext=(-290, -110), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2") ) plt.plot(x_data, y_data, 'bo--', label=u"Faster D latch and XOR", linewidth=2) plt.plot(x_data3, y_data3, 'c', label=u"The Ideal Curve", linewidth=2) plt.title(u"$2\pi$ phase detector", size=20) plt.legend(loc=0) # 顯示 label # 移動坐標(biāo)軸代碼 ax = gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xlabel(u"$\phi/rad$", size=20) # 角度單位為 pi plt.ylabel(u"$DC/V$", size=20) plt.xticks([0, 0.5, 1, 1.5, 2], [r'$0$', r'$\pi/2$', r'$\pi$', r'$1.5\pi$', r'$2\pi$'], size=16) for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) plt.grid(True)
與我們最開始那張圖比起來,是不是有種脫胎換骨的感覺?這其中,對圖像與坐標(biāo)軸相交的部分,做了透明化處理,代碼為:
for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
透明度由其中的參數(shù) alpha=0.65
控制,如果想更透明,就把這個數(shù)改到更小,0 代表完全透明,1 代表不透明。而改變橫軸坐標(biāo)顯示方式的代碼為:
plt.xticks([0, 0.5, 1, 1.5, 2], [r'$0$', r'$\pi/2$', r'$\pi$', r'$1.5\pi$', r'$2\pi$'], size=16)
這里直接手動指定 x 軸的標(biāo)度。依然是使用 LaTeX 引擎來表示數(shù)學(xué)公式。
實(shí)驗總結(jié)
本次實(shí)驗使用 Python 的繪圖包 Matplotlib 繪制了一副圖像。圖像的數(shù)據(jù)來源于 Excel 數(shù)據(jù)表。與使用數(shù)據(jù)表畫圖相比,通過程序控制繪圖,得到了更加靈活和精細(xì)的控制,最終繪制除了一幅精美的圖像。
到此這篇關(guān)于Python從Excel讀取數(shù)據(jù)并使用Matplotlib繪制成二維圖像的文章就介紹到這了,更多相關(guān)Python讀取Excel數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python的math模塊中的常用數(shù)學(xué)函數(shù)整理
這篇文章主要介紹了Python的math模塊中的常用數(shù)學(xué)函數(shù)整理,同時對運(yùn)算符的運(yùn)算優(yōu)先級作了一個羅列,需要的朋友可以參考下2016-02-02python關(guān)鍵字傳遞參數(shù)實(shí)例分析
在本篇文章里小編給大家整理的是一篇關(guān)于python關(guān)鍵字傳遞參數(shù)實(shí)例分析內(nèi)容,有需要的朋友們可以學(xué)習(xí)參考下。2021-06-06python將秒數(shù)轉(zhuǎn)化為時間格式的實(shí)例
今天小編就為大家分享一篇python將秒數(shù)轉(zhuǎn)化為時間格式的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09Python中用startswith()函數(shù)判斷字符串開頭的教程
這篇文章主要介紹了Python中用startswith()函數(shù)判斷字符串開頭的教程,startswith()函數(shù)的使用是Python學(xué)習(xí)中的基礎(chǔ)知識,本文列舉了一些不同情況下的使用結(jié)果,需要的朋友可以參考下2015-04-04