实验介绍
本课程实现使用 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
里的每一行每一列数据都读取出来即可。很明显,这是个循环过程。
## 下载所需示例数据
## 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
进行循环,这是最外层循环。 - 在每个
sheet
内,进行第二次循环,行循环。 - 在每行内,进行列循环,这是第三层循环。
在最内层列循环内,取出行列值,复制到新建的 values
列表内,很明显,源数据有几列,values
列表就有几个元素。我们例子中的 Excel 文件有两列,分别对应角度和 DC 值。所以在列循环结束后,我们将取得的数据保存到 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