Python data display exercise (1)


foreword

Use Pandas to read excel files, extract and process data; use Matplotlib for data visualization, practice area division and chart improvement.


1. Area division exercise

(1) Import library

import pandas as pd
import matplotlib.pyplot as plt
from math import ceil#向上取整

(2) Set the file path, extracted content, and display form

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) Loop read and process data, drawing

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) Save and display the picture

plt.tight_layout()#调整间距
plt.savefig(p_path, dpi=600)
plt.show()

(5) Result display

2. Diagram Perfection Exercise

(1) Import library

import pandas as pd
import matplotlib.pyplot as plt

(2) Set the file path, the data to be extracted, the legend and the added text

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) Read and process data

#读取数据
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) Draw and improve the chart


#绘图  
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) Result display
insert image description here


Summarize

Use the Pandas library to easily read and process data in Excel files. It is more convenient and flexible to modify the code according to actual needs than to use the same code in all cases.

Guess you like

Origin blog.csdn.net/qq_53715621/article/details/125352282