記事ディレクトリ
序文
Pandas を使用して Excel ファイルを読み取り、データを抽出および処理し、Matplotlib を使用してデータの視覚化、実践領域の分割、グラフの改善を行います。
1. エリア分割演習
(1) インポートライブラリ
import pandas as pd
import matplotlib.pyplot as plt
from math import ceil#向上取整
(2) ファイルパス、抽出内容、表示形式を設定する
f_path = './data/test.xls'#文件位置
p_path = './data/test'#图片位置
sheets = ['Data']#工作表
labels = ['TimeOutput', 'I']#数据列
append_num = 18#工作表数目
for i in range(append_num):
sheets.append('Append'+str(i+1))
col = 4#列数
row = ceil(len(sheets)/4)#行数
fig = plt.figure(figsize=(12, 6))#创建图表
(3) データの読み込みと処理、描画をループする
for i, sheet in enumerate(sheets):
#读取数据
print('{}/{}'.format(i+1,append_num+1),sheet)
d = pd.read_excel(f_path, sheet_name=sheet, header=0, usecols=labels)
x = d[labels[0]]
y = d[labels[1]]
#绘图
ax = fig.add_subplot(row, col, i+1)#添加区域
ax.plot(x, y, 'b-')
ax.set_title(sheet)
ax.set_xlabel(labels[0])
ax.set_ylabel(labels[1])
(4) 画像を保存して表示する
plt.tight_layout()#调整间距
plt.savefig(p_path, dpi=600)
plt.show()
(5) 結果表示
2. 図の完成演習
(1) インポートライブラリ
import pandas as pd
import matplotlib.pyplot as plt
(2) ファイルパス、抽出するデータ、凡例、追加するテキストを設定します
f_path = './data/test.xls'#文件位置
p_path = './data/test0'#图片位置
sheet = 'Data'#工作表
cols = ['TimeOutput', 'I']#数据列
labels = ['Time(s)', 'Current(μA)']#坐标轴
lgd = '1-0-1'#图例
text = 'WRITE:-3V,100ms\nREAD:-0.6V,200μs'#文本
(3) データの読み取りと処理
#读取数据
d = pd.read_excel(f_path, sheet_name=sheet, header=0, usecols=cols)
x = d[cols[0]]
y = d[cols[1]]
#数据处理
y = y*10**6
(4) チャートを描いて完成させる
#绘图
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(x, y, 'b-')
plt.rcParams['xtick.direction'] = 'in'#刻度线向内
plt.rcParams['ytick.direction'] = 'in'
ax.set_xlabel(labels[0])#坐标轴
ax.set_ylabel(labels[1])
ax.legend([lgd], fontsize=10, loc='upper right', frameon=False)#图例
ax.text(0.05, 0.85, text, fontsize=10, transform=ax.transAxes)#文本
plt.savefig(p_path, dpi=600)
plt.show()
(5) 結果表示
要約する
Excel ファイル内のデータは、Pandas ライブラリを使用して簡単に読み取り、処理できます。すべての場合に同じコードを使用するよりも、実際のニーズに応じてコードを変更する方が便利で柔軟です。