python 读取csv,绘制数据
- 从csv目录下读取所有 csv,合并输出到 out.csv
csv目录下,文件名格式:
{数字}_*.csv
- 读取 out.csv ,第1列是横坐标,第2列及后面的列都是纵坐标
testPlot.py
import glob
import re
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import threading
prefix="csv\\"
files='*.csv'
path = prefix+files
outFile = "out.csv"
def plotGraph():
print("show graph")
data=pd.read_csv(outFile)
headers = data.columns
agnles=data[headers[0]]
for hd in headers:
print("hd:",hd)
if hd == "angle":
continue
list = data[hd].values
plt.plot(agnles,list,label=hd)
plt.legend(loc='upper right',ncol=2,bbox_to_anchor=(1.1, 1))
plt.xlabel('angles')
plt.ylabel('values')
plt.xticks(np.arange(math.floor(agnles.min()-5), round(agnles.max()+5),step=5))
plt.grid()
plt.title("test plot")
plt.show()
if __name__ == '__main__':
print("merge csv files")
index = 0
dataframe = pd.DataFrame()
agnles=[]
fileList =[]
for file_name in glob.glob(path):
file_name = file_name.removeprefix(prefix)
fileList.append(file_name)
fileList.sort(key=lambda i:int(re.match(r'(\d+)',i).group()))
for file_name in fileList:
print("========== file_name:{} ==========".format(file_name))
data = pd.read_csv(prefix+"/"+file_name,header=None)
if index==0:
agnles=data.iloc[:,[0]]
dataframe["angle"]=agnles
list = data.iloc[:,[1]]
colName = ("ch{}".format(index))
dataframe[colName]=list
index+=1
dataframe.to_csv(outFile,header=True,index=False,sep=',')
plotGraph()
print("主线程结束\n")
效果