前景概要

为什么生成的是csv文件而不是txt文件 因为txt在python那边处理起来比较麻烦 需要两组数 而数与数之间存在对应关系 这样两组数同样需要两组 就是两组xy数值 然后将两组x对齐通过折线图的形式对比y值

C++生成csv代码

每次open都会对文件内容进行刷新 但是我还不太想让open和输入距离太远 所以这里采取的是在文件末尾追加的形式 但是每次重新运行都要在文件输出的位置新建和程序同名文件

std::ofstream out;
std::string   ss;
out.open("ubuntu绝对路径从根路径开始", std::ios::out |std::ios::app);
if (!out.is_open())
{
std::cout << "file is not open" << std::endl;
}
out.precision(4);
out << time << ",";
out << theta << std::endl;
out.close();

precision函数对精度进行控制
csv文件作为输出时 ","为分列输出 同样endl为换行输出

Python代码读取csv文件并使用matplotlib绘图

import csv
#用于读取csv文件
import matplotlib
#用于绘图
import matplotlib.pyplot as plt
from numpy import *
#用于求列表平均数
if __name__ == '__main__':
    filename = '文件1的位置'
    filename2 = '文件2的位置'
    data = {}
    data2 = {}
    dic = []
    timestamp = []
    theta_z = []
    timestamp2 = []
    theta_z2 = []
    with open(filename) as csvfile:
        next(csvfile)
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            data[row[0]] = row[1]
            #float用于将字符串转化为浮点数
            time1.append(float(row[0]))
            theta1.append(float(row[1]))
    print(data)

    with open(filename2) as csvfile:
        next(csvfile)
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            data2[row[0]] = row[1]
            time2.append(float(row[0]))
            theta2.append(float(row[1]))
    print(data2)
	#round函数用于控制精度
    time_ = [round(i, 4)for i in time1]
    theta_ = [round(i, 4)for i in theta1]
    #求列表平均数
    theta_mean = mean(theta_z_)

    time_2 = [round(i, 4)for i in time2]
    theta_2 = [round(i, 4) for i in theta2]

	#将两组数据输出在一个图上做对比
    plt.plot(time_, theta_)
    plt.plot(time_2, theta_2)
    plt.show()