我有一个包含四列的 csv 文件。第一列是时间,第二列、第三列和第四列是加速度计读数。我想在 X 轴上绘制时间,在 Y 轴上绘制加速度计读数。
示例数据:
0 1.0969 9.7721 0.614
20 1.1146 9.7501 0.7444
40 1.1146 9.7501 0.7444
60 1.0124 9.7151 0.7169
79 1.0124 9.7151 0.7169
100 1.0927 9.7324 0.7356
120 1.0927 9.7324 0.7356
这是我目前所拥有的。
from numpy import genfromtxt
import csv
import matplotlib.pyplot as plt
#import numpy as np
# Open the desired file for reading
f = open('walk-shoe.csv', "rb")
# create a object of csv class and read the file
# use ',' as a delimiter
reader = csv.reader(f, delimiter=',')
time_row = 0
accel_1_row = 0
accel_2_row = 0
accel_3_row = 0
time = []
accel_1 = []
accel_2 = []
accel_3 = []
# create a list of 'Time in ms'
for row in reader:
# Skip the first row
time_row = time_row + 1
if time_row == 1:
continue
time.append(row[0])
accel_1.append(row[1])
accel_2.append(row[2])
accel_3.append(row[3])
# print the contents of the list
# print time
#print accel_1
#print accel_2
#print accel_3
# append all the list accelerometer list together
final_accel = []
final_accel.append(accel_1)
final_accel.append(accel_2)
final_accel.append(accel_3)
#print final_accel
# plot the graph
for i in range(len(final_accel)):
plt.plot(time,[pt[i] for pt in final_accel],label = 'id %s'%i)
plt.legend()
plt.show()
我想在一张图上绘制 y 轴上的所有传感器读数和 x 轴上的时间
最佳答案
您似乎在您提供的代码中导入了 numpy,因此我认为这意味着您可以使用该库。 Numpy 让您可以使用 numpy.loadtxt()
非常轻松地读取数据.
然后您可以创建一个 for 循环,遍历第 1 列到第 3 列,并针对第 0 列(时间)绘制数据。
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('walk-shoe.csv', delimiter=',', dtype=float)
print (data)
#[[ 0. 1.0969 9.7721 0.614 ]
# [ 20. 1.1146 9.7501 0.7444]
# [ 40. 1.1146 9.7501 0.7444]
# [ 60. 1.0124 9.7151 0.7169]
# [ 79. 1.0124 9.7151 0.7169]
# [ 100. 1.0927 9.7324 0.7356]
# [ 120. 1.0927 9.7324 0.7356]]
for i in range(1,data.shape[1]):
plt.plot(data[:,0], data[:,i], label='id %s' %i)
plt.legend()
plt.show()
关于python - 通过从 CSV 中读取列来绘制图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310851/