一個小例子集合xlrd,matplotlib,numpy,scipy使用方法(從Excel導入數據)

最近因爲一篇論文的原因,要從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 np
import matplotlib,pyplot as plt
#我們利用上面得到的數據進行處理
#生成一個X軸array
x = np.arange(1,len(data_col)+1,1)
#利用導入的Excel表格獲得的list類型的數據賦值給y
y = np.array(data_col)
#繪製x,y的圖像
plt.plot(x,y,label = "test",fontsize = 15)
#添加橫座標
plt.xlabel("time")
添加縱座標
plt.ylabel("displacement")
#添加legend
plt.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 plt
import numpy as np
import xlrd
from scipy.interpolate import spline

book = 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 = 0
for 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.0

row_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的提及方法簡介

#獲得一個初值,終值,步長的array
numpy.arange([start, ]stop, [step, ])
    Return evenly spaced values within a given interval.

#傳入一個list直接生成array
numpy.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 fit
Parameters: 
    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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章