提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
数据分析记录
一、需求
两个数据源,总的采样时间相同,但是采样周期不同,绘制在同一张折线图上进行对比分析。
二、步骤
1.提取数据
代码如下:
#!/usr/bin/python3
import os
# key words to extract
# str_start = "R: ["
str_start = "L: ["
str_end = "]"
str_start_len = len(str_start)
f_orig = open('velData_1.txt') # original file
f_extra = open('velData_save_L.txt', 'w') # target file used to save
# f_extra = open('velData_save_R.txt', 'w') # target file used to save
line = f_orig.readline()
while line:
# find index according to the key words
index_start = line.find(str_start)
index_end = line.find(str_end)
text = line[index_start : index_end]
if text != '':
# If there is more than one [], we can use "extra" and "End" as str_start and str_end
f_extra.write(str(line[index_start + str_start_len : index_end]) + '\n')
line = f_orig.readline()
f_orig.close()
f_extra.close()
2.读入数据并绘图
代码如下:
# encoding=utf-8
from matplotlib import pyplot
import matplotlib.pyplot as plt
import numpy as np
from fractions import gcd
import sys
lidar_file = "velData_save_L.txt"
lidar = []
with open(lidar_file) as f:
for line in f:
lidar.extend([float(i) for i in line.split()])
radar_file = "velData_save_R.txt"
radar = []
with open(radar_file) as fr:
for line in fr:
radar.extend([float(m) for m in line.split()])
print(lidar)
print(radar)
source_one_y = lidar
source_two_y = radar
# 由于range的采样间隔不能为小数,于是先求最小公倍数。
LeastCommonMultiple = len(source_one_y)*len(source_two_y)/gcd(len(source_one_y),len(source_two_y)) # 最小公倍数
source_one_x = range(0,LeastCommonMultiple,LeastCommonMultiple/len(source_one_y))
source_two_x = range(0,LeastCommonMultiple,LeastCommonMultiple/len(source_two_y))
plt.plot(source_one_x, source_one_y,label='source_one', linestyle = 'solid')
plt.plot(source_two_x, source_two_y,label='source_two', linestyle = 'dotted')
plt.legend() # 让图例生效
# # 设置横轴记号
# pyplot.xticks(np.arange(0, 500, 100))
plt.margins(0)
plt.subplots_adjust(bottom=0.10)
plt.xlabel('Sample Time') # X轴标签
plt.ylabel("velocity km/h") # Y轴标签
pyplot.yticks(np.arange(0, 50, 2))
plt.title("A simple plot") # 标题
plt.show()
效果如下
总结
后续将优化绘图效果