您的位置:首页 > 编程语言 > Python开发

一个小例子集合xlrd,matplotlib,numpy,scipy使用方法(从Excel导入数据)

2017-04-13 21:58 766 查看
最近因为一篇论文的原因,要从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 StringLocation 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python