最近因為一篇論文的原因,要從Excel中取得部分資料平作圖,但是得到的圖都是位元影像,不是太好插入到論文中,因此,決定使用Python畫圖來解決此問題(不使用MATLAB的原因在於它畫出的圖是在是不好看呀)
首先使用的庫是xlrd庫,此庫的作用是從讀取Excel資料
#對應的所有例子中使用的方法貼到了文章最後,方便尋找import xlrd#首先執行個體化一個book對象book = xlrd.open_workbook("一個Excel地址")#然後擷取這個book的所有sheet名稱,返回一個列表sheetName = book.sheet_names()#擷取sheet類的一個對象,也就是說,如果知道每個sheet的名字的話,就可以直接用sheet的名字來執行個體化它了sheet1 = book.sheet_by_name(sheetName[0])#然後我們去獲得這個對象的列的資料,比如下面一行獲得是sheet1也就是第一個sheet的第一列的前40個資料,格式為一個列表data_col = sheet1.col_values(0)[0:40]#到目前為止,我們已經實現了獲得資料的目的
然後使用的是庫numpy,matplotlib庫
import numpy as npimport matplotlib,pyplot as plt#我們利用上面得到的資料進行處理#產生一個X軸arrayx = np.arange(1,len(data_col)+1,1)#利用匯入的Excel表格獲得的list類型的資料賦值給yy = np.array(data_col)#繪製x,y的映像plt.plot(x,y,label = "test",fontsize = 15)#添加橫座標plt.xlabel("time")添加縱座標plt.ylabel("displacement")#添加legendplt.legend(loc = 0)plt.show()
期間,會用到scipy庫,目的是smooth曲線
from scipy.interpolate import spline#使用方法如下xnew = np.linspace(x.min(),x.max(),300)ynew = spline(x,y,xnew)#現在就可以使用如下方式畫出smooth的圖plt.plot(xnew,ynew)
如何?一個畫布多個圖以及雙Y軸圖的繪製
#實現一個畫布多個圖的方法#plt.subplot(rows,cols,num),需要繪製的每個圖之前使用這個,然後修改代表每個圖位置的第三個參數plt.subplot(2,2,1)#實現雙Y軸的方法plt.twinx()
附上一個完整的例子,代碼寫的不規範
import matplotlib.pyplot as pltimport numpy as npimport xlrdfrom scipy.interpolate import splinebook = xlrd.open_workbook("國網資料-位移-加速度.xls")sheet = book.sheet_names()[0:4]# print(sheet)sheet_con = []for data in sheet: sheet_con.append(book.sheet_by_name(data))# print(sheet_con)i = 0for all_data in sheet_con: y1 = all_data.col_values(0)[1:40] y2 = all_data.col_values(1)[1:40] x = np.arange(1,len(y1)+1,1) i = i + 1 xnew = np.linspace(x.min(),x.max(),600) y1 = spline(x,y1,xnew) y2 = spline(x,y2,xnew) plt.subplot(2,2,i) plt.plot(xnew,y1,"b",linewidth = 2,label = "acceleration") plt.legend(loc = 2) plt.xlabel("time/(0.1s)") if i == 1 or i == 3: plt.ylabel("acceleration of X/(g)") else: plt.ylabel("acceleration of Z/(g)") plt.twinx() plt.plot(xnew,y2,"r--",linewidth = 2,label = "displacement") plt.legend(loc = 3) if i == 1 or i == 2: plt.ylabel("displacement of label 1/(mm)") else: plt.ylabel("displacement of label 2/(mm)")# plt.title("relationship between acceleration and displacement")plt.show()
xlrd有關方法簡介
#擷取這個sheet_name對應的sheet對象sheet_by_name(sheet_name) [#] sheet_name Name of sheet required Returns: An object of the Sheet class#擷取book對象中所有的sheet的名字(返回列表形式)sheet_names() [#] Returns: A list of the names of the sheets in the book.#擷取book中所有sheet的地址sheets() [#] Returns: A list of all sheets in the book.col_slice(colx, start_rowx=0, end_rowx=None) [#] Returns a slice of the Cell objects in the given column.col_types(colx, start_rowx=0, end_rowx=None) [#] Returns a slice of the types of the cells in the given column.#sheet對象的一個方法,擷取此sheet對象的第colx列,從start_rowx到end_rowx中所有data的列表col_values(colx, start_rowx=0, end_rowx=None) [#] Returns a slice of the values of the cells in the given column.name [#] Name of sheet.#擷取sheet對象中column的列數ncols [#] Number of columns in sheet. A column index is in range(thesheet.ncols).#擷取sheet對象中row行數nrows [#] Number of rows in sheet. A row index is in range(thesheet.nrows).row(rowx) [#] Returns a sequence of the Cell objects in the given row.row_label_ranges [#] List of address ranges of cells containing row labels. For more details, see col_label_ranges above. -- New in version 0.6.0row_slice(rowx, start_colx=0, end_colx=None) [#] Returns a slice of the Cell objects in the given row.row_types(rowx, start_colx=0, end_colx=None) [#] Returns a slice of the types of the cells in the given row.row_values(rowx, start_colx=0, end_colx=None) [#] Returns a slice of the values of the cells in the given row.以上摘自http://www.lexicon.net/sjmachin/xlrd.html
這是一個關於numpy與matplotlib的提及方法簡介
#獲得一個初值,終值,步長的arraynumpy.arange([start, ]stop, [step, ]) Return evenly spaced values within a given interval.#傳入一個list直接產生arraynumpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0) return an array. object : array_like——An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.#label指的是次線條的標籤,linewieth是線寬,fontsize是字型大小plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2,fontsize = 15)#xlabel設定matplotlib.pyplot.xlabel(s, *args, **kwargs) Set the x axis label of the current axis. Default override is: override = { 'fontsize' : 'small', 'verticalalignment' : 'top', 'horizontalalignment' : 'center' }#legend設定,location的數字代表的位置plt.legend(loc = 0)
| Location String |
Location Code |
| ‘best’ |
0 |
| ‘upper right’ |
1 |
| ‘upper left’ |
2 |
| ‘lower left’ |
3 |
| ‘lower right’ |
4 |
| ‘right’ |
5 |
| ‘center left’ |
6 |
| ‘center right’ |
7 |
| ‘lower center’ |
8 |
| ‘upper center’ |
9 |
| ‘center’ |
10 |
#產生一個初值終值為範圍,以num為均勻的間隔點的一個樣本numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) Return evenly spaced numbers over a specified interval. Returns num evenly spaced (間隔均勻的) samples, calculated over the interval [start, stop]. The endpoint of the interval can optionally be excluded.#一畫布多圖片matplotlib.pyplot.subplot(*args, **kwargs) Return a subplot axes positioned by the given grid definition. Typical call signature: #畫布中,映像的分布位置 subplot(nrows, ncols, plot_number) Where nrows and ncols are used to notionally split the figure into nrows * ncols sub-axes, and plot_number is used to identify the particular subplot that this function is to create within the notional grid. plot_number starts at 1, increments across rows first and has a maximum of nrows * ncols. In the case when nrows, ncols and plot_number are all less than 10, a convenience exists, such that the a 3 digit number can be given instead, where the hundreds represent nrows, the tens represent ncols and the units represent plot_number#雙Y軸方法的實現matplotlib.pyplot.twinx(ax=None) Make a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None). The ticks for ax2 will be placed on the right, and the ax2 instance is returned.
關於scipy的方法
scipy.interpolate.spline(*args, **kwds)[source]Interpolate a curve at new points using a spline fitParameters: xk, yk : array_like The x and y values that define the curve. xnew : array_like The x values where spline should estimate the y values.地址:https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#spline-interpolation