Python從Excel讀取數據并使用Matplotlib繪制成二維圖像
知識點
- 使用 xlrd 擴展包讀取 Excel 數據
- 使用 Matplotlib 繪制二維圖像
- 顯示 LaTeX 風格公式
- 坐標點處透明化
接下來,我們將通過實踐操作,帶領大家使用 Python 實現從 Excel 讀取數據繪制成精美圖像。
首先,我們來繪制一個非常簡單的正弦函數,代碼如下:
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 擴展包
xlrd 顧名思義,就是 Excel 文件的后綴名 .xl
文件 read
的擴展包。這個包只能讀取文件,不能寫入。寫入需要使用另外一個包。但是這個包,其實也能讀取.xlsx
文件。
從 Excel 中讀取數據的過程比較簡單,首先從 xlrd 包導入 open_workbook
,然后打開 Excel 文件,把每個 sheet
里的每一行每一列數據都讀取出來即可。很明顯,這是個循環(huán)過程。
## 下載所需示例數據 ## 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])
如果安裝包沒有問題,這段代碼應該能打印出 Excel 表中的數據內容。解釋一下這段代碼:
- 打開一個 Excel 文件后,首先對文件內的
sheet
進行循環(huán),這是最外層循環(huán)。 - 在每個
sheet
內,進行第二次循環(huán),行循環(huán)。 - 在每行內,進行列循環(huán),這是第三層循環(huán)。
在最內層列循環(huán)內,取出行列值,復制到新建的 values
列表內,很明顯,源數據有幾列,values
列表就有幾個元素。我們例子中的 Excel 文件有兩列,分別對應角度和 DC 值。所以在列循環(huán)結束后,我們將取得的數據保存到 x_data1
和 y_data1
這兩個列表中。
繪制圖像 V1
第一個版本的功能很簡單,從 Excel 中讀取數據,然后繪制成圖像。同樣先下載所需數據:
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 中讀取數據的程序,上面已經解釋過了。這段代碼后面的函數是 Matplotlib 繪圖的基本格式,此處的輸入格式為:plt.plot(x 軸數據, y 軸數據, 曲線類型, 圖例說明, 曲線線寬)
。圖片頂部的名稱,由 plt.title(u"TR14 phase detector")
語句定義。最后,使用 plt.legend()
使能顯示圖例。
繪制圖像 V2
這個圖只繪制了一個表格的數據,我們一共有三個表格。但是就這個一個已經夠丑了,我們先來美化一下。首先,坐標軸的問題:橫軸的 0 點對應著縱軸的 8,這個明顯不行。我們來移動一下坐標軸,使之 0 點重合:
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")
好的,移動坐標軸后,圖片稍微順眼了一點,我們也能明顯的看出來,圖像與橫軸的交點大約在 180 度附近。
解釋一下移動坐標軸的代碼:我們要移動坐標軸,首先要把舊的坐標拆了。怎么拆呢?原圖是上下左右四面都有邊界刻度的圖像,我們首先把右邊界拆了不要了,使用語句 ax.spines['right'].set_color('none')
。
把右邊界的顏色設置為不可見,右邊界就拆掉了。同理,再把上邊界拆掉 ax.spines['top'].set_color('none')
。
拆完之后,就只剩下我們關心的左邊界和下邊界了,這倆就是 x
軸和 y
軸。然后我們移動這兩個軸,使他們的零點對應起來:
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))
這樣,就完成了坐標軸的移動。
繪制圖像 V3
我們能不能給圖像過零點加個標記呢?顯示的告訴看圖者,過零點在哪,就免去看完圖還得猜,要么就要問作報告的人。
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")
好的,加上標注的圖片,顯示效果更好了。標注的添加,使用 plt.annotate(標注文字, 標注的數據點, 標注文字坐標, 箭頭形狀) 語句。這其中,標注的數據點是我們感興趣的,需要說明的數據,而標注文字坐標,需要我們根據效果進行調節(jié),既不能遮擋原曲線,又要醒目。
繪制圖像 V4
我們把三組數據都畫在這幅圖上,方便對比,此外,再加上一組理想數據進行對照。這一次我們再做些改進,把橫坐標的單位用 LaTeX 引擎顯示;不光標記零點,把兩邊的非線性區(qū)也標記出來;
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 # 移動坐標軸代碼 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 表示數學公式,使用 $$
表示兩個符號之間的內容是數學符號。圓周率就可以簡單表示為 $\pi$
,簡單到哭,顯示效果卻很好看。同樣的,$\phi$
表示角度符號,書寫和讀音相近,很好記。
對于圓周率,角度公式這類數學符號,使用 LaTeX 來表示,是非常方便的。這張圖比起上面的要好看得多了。但是,依然覺得還是有些丑。好像用平滑線畫出來的圖像,并不如用點線畫出來的好看。而且點線更能反映實際的數據點。此外,我們的圖像跟坐標軸重疊的地方,把坐標和數字都擋住了,看著不太美。
圖中的理想曲線的數據,是根據電路原理純計算出來的,要講清楚需要較大篇幅,這里就不展開了,只是為了配合比較而用,這部分代碼,大家知道即可:
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
我們再就上述問題,進行優(yōu)化。優(yōu)化的過程包括:改變橫坐標的顯示,使用弧度顯示;優(yōu)化圖像與橫坐標相交的部分,透明顯示;增加網絡標度。
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 # 移動坐標軸代碼 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)
與我們最開始那張圖比起來,是不是有種脫胎換骨的感覺?這其中,對圖像與坐標軸相交的部分,做了透明化處理,代碼為:
for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
透明度由其中的參數 alpha=0.65
控制,如果想更透明,就把這個數改到更小,0 代表完全透明,1 代表不透明。而改變橫軸坐標顯示方式的代碼為:
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 軸的標度。依然是使用 LaTeX 引擎來表示數學公式。
實驗總結
本次實驗使用 Python 的繪圖包 Matplotlib 繪制了一副圖像。圖像的數據來源于 Excel 數據表。與使用數據表畫圖相比,通過程序控制繪圖,得到了更加靈活和精細的控制,最終繪制除了一幅精美的圖像。
到此這篇關于Python從Excel讀取數據并使用Matplotlib繪制成二維圖像的文章就介紹到這了,更多相關Python讀取Excel數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python中用startswith()函數判斷字符串開頭的教程
這篇文章主要介紹了Python中用startswith()函數判斷字符串開頭的教程,startswith()函數的使用是Python學習中的基礎知識,本文列舉了一些不同情況下的使用結果,需要的朋友可以參考下2015-04-04