A small example collection xlrd,matplotlib,numpy,scipy use method (import data from Excel)

Source: Internet
Author: User

The reason for a paper recently, to get some data from Excel to draw, but the resulting figure is a bitmap, not too good to insert into the paper, so decided to use Python paint to solve this problem (not using MATLAB because it is the picture is not good-looking)

The first library to use is the XLRD library, which functions from reading Excel data

#对应的所有例子中使用的方法贴到了文章最后, easy to find
import xlrd
#首先实例化一个book对象 book
= Xlrd.open_workbook ("One Excel Address")
# Then get all the sheet names for this book and return a list
sheetname = Book.sheet_names ()
#获取sheet类的一个对象, that is, if you know the name of each sheet, You can instantiate it directly with sheet's name
Sheet1 = book.sheet_by_name (sheetname[0))
#然后我们去获得这个对象的列的数据, For example, the following line obtains the first 40 data of the Sheet1, the first column of the sheet, in the form of a list
Data_col = sheet1.col_values (0) [0:40]

#到目前为止, We've achieved the goal of getting the data.

And then use the Library Numpy,matplotlib Library

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 image
Plt.plot (X,y,label = "Test", FontSize =
#添加横坐标
plt.xlabel ("Time")
Add ordinate
plt.ylabel ("displacement")
# Add Legend
plt.legend (loc = 0)
plt.show ()

Period, the SciPy library is used to smooth the curve

From scipy.interpolate import spline
#使用方法如下
xnew = Np.linspace (X.min (), X.max (), +)
ynew = spline (x,y , xnew)
#现在就可以使用如下方式画出smooth的图
plt.plot (xnew,ynew)

how to achieve the drawing of a canvas with multiple graphs and a double y-axis diagram

#实现一个画布多个图的方法
#plt. Subplot (Rows,cols,num), use this before each diagram you draw, and then modify the third parameter representing the position of each diagram
Plt.subplot (2,2,1)

# method to implement double y-axis
Plt.twinx ()

attach a complete example of code written by nonstandard

Import Matplotlib.pyplot as PLT import numpy as NP import xlrd from scipy.interpolate import spline book = Xlrd.open_work Book ("National Network data-displacement-acceleration. xls") sheet = book.sheet_names () [0:4] # Print (sheet) Sheet_con = [] for data in Sheet:sheet_con.app
    End (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 (), Y1 = spline (x,y1,xnew) y2 = spline (x,y2,xnew) Plt.subplot (2,2,i) plt.plot (xnew,y1, "B", linewidth = 2,l Abel = "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--", L Inewidth = 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 About method Introduction

#获取这个sheet_name对应的sheet对象 Sheet_by_name (Sheet_name) [#] Sheet_name name of sheet required Returns:an Obje CT of the Sheet class #获取book对象中所有的sheet的名字 (return list form) 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对象的一个方法, get the Colx column of this sheet object, from start_rowx to End_rowx list of all 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 the Cell objects in the given row. row_label_ranges [#] List of address ranges of cells containing row labels. 
    For more details, 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 G

Iven 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. Above excerpted from http://www.lexicon.net/sjmachin/xlrd.html

This is a brief introduction to the NumPy and Matplotlib reference method

#获得一个初值, end value, step length array
numpy.arange ([Start,]stop, [step,]) return
    evenly spaced values within a given interval.< c3/> #传入一个list直接生成array
Numpy.array (object, Dtype=none, Copy=true, order= ' K ', Subok=false, ndmin=0)
    return Array.
    Object:array_like--an array, any object exposing the array interface, a object whose __array__ method returns an array, or any (nested) sequence.

#label指的是次线条的标签, Linewieth is the line width, fontsize is the font size
plot ([1,2,3], [1,2,3], ' go-', label= ' lines 1 ', linewidth=2,fontsize =

#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's number is represented by the position
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 ' ten
#生成一个初值终值为范围, a sample of Numpy.linspace (Start, Stop, num=50, Endpoint=true, Retstep=false, Dtype=none) return EV with NUM as the uniform interval point
    Enly spaced numbers over a specified interval.
    Returns num evenly spaced (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: #画布中, the distribution position of the image subplot (nrows, Ncols, Plot_number) where nrows and Ncols are to.  Ionally split the figure into nrows * Ncols sub-axes, and plot_number are used to identify the particular subplot The function is to create within the notional grid.
    Plot_number starts at 1, increments across rows A and has a maximum of nrows * ncols. In the "case" nrows, Ncols and Plot_number are all less than, a convenience exists, such that the a 3 digit number C An is given instead, where the hundreds RepresenT nrows, the Tens represent ncols and the units represent #双Y轴方法的实现 Plot_number (Matplotlib.pyplot.twinx) make A second axes that shares the x-axis. The new axes would overlay ax (or the current axes if Ax is None). The ticks for AX2 would be placed on the right and the AX2 instance is returned.

a method of scipy

Scipy.interpolate.spline (*args, **kwds) [source]
interpolate a curve in 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.
Address: Https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#spline-interpolation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.