数据写入文本并可视化(C++,Python)

平时开发时经常需要将过程数据记录写入文本并进行可视化,最常用的是写入一个数组或列表等,表示力、速度、位姿,在此记录C++和Python写入的函数,方便后续自己查看。

【C++】

void write_list(double* force, const std::string& filename) {
    std::ostringstream oss;
    for (size_t i = 0; i < 6; ++i) {
        if (i > 0) {
            oss << ",";
        }
        oss << force[i];
    }

    std::ofstream ofs(filename, std::ios::app);
    if (ofs.is_open()) {
        ofs << "\n" << oss.str();
        ofs.close();
    } else {
        std::cerr << "Error opening file: " << filename << std::endl;
    }
}

【Python】

def write_list(pos,filename):
    list1 = ( ",".join( repr(e) for e in pos))        
    with open(filename,'a') as f:
        f.write('\n'+str(list1))

记录后在txt文本的数据如下:

0.008999999612569809,0.01600000075995922,-0.009999999776482582,-0.0,-0.0,-0.0
0.020999999716877937,0.03500000014901161,0.0010000000474974513,-0.0,-0.0,-0.0
0.003000000026077032,0.013000000268220901,-0.008999999612569809,-0.0,-0.0,-0.0
0.02199999988079071,0.035999998450279236,-0.010999999940395355,-0.0,-0.0,-0.0
0.03400000184774399,0.02800000086426735,-0.01899999938905239,-0.0,-0.0,-0.0

【绘图】

绘图采用Pyhon,这里绘制前三列的数据,可根据需要修改

# 绘制轨迹
# coding:utf-8
import matplotlib.pyplot as plt
import numpy as np


# 读取文件函数,返回第三个数的列表
def read_from_file(filename):
    pos = []
    with open(filename, 'r') as f:
        for line in f:
            # strip()去除空行
            # print(line.strip().split(","))
            if len(line) > 1:
                values = [float(x) for x in line.strip().split(",")]
                pos.append(values)
    return pos

def main():
    # 文件路径
    file1 = 'force.txt'
    force = read_from_file(file1)
    # 转换为NumPy数组,方便处理
    force = np.array(force)
    # 提取 x,y,z方向的力
    force_x = force[:, 0]
    force_y = force[:, 1]
    force_z = force[:, 2]

    # 绘制图形
    plt.figure(figsize=(12, 6))
    plt.plot(force_x, color='blue', label='x')
    plt.plot(force_y, color='red', label='y')
    plt.plot(force_z, color='green', label='z')
    plt.xlabel('num')
    plt.ylabel('force')
    plt.title('the curve of force')
    plt.legend()
    # plt.axis('equal')
    plt.grid(True)

    plt.show()


if __name__ == '__main__':
    main()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值