python - 通过从 CSV 中读取列来绘制图表

标签 python python-2.7 csv matplotlib plot

我有一个包含四列的 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()

enter image description here

关于python - 通过从 CSV 中读取列来绘制图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310851/

相关文章:

python-2.7 - Python 隐藏 ^C 从 SIGINT

java - 如何在Java中连接2个csv文件

python - django.core.urlresolver.reverse - NoReverseMatch : Reverse for '...' with arguments '()' and keyword arguments '{}' not found

python - 如何在将图像提供给 CoreML 模型之前对其进行预处理?

python - request.get(url) 以纪元格式返回日期 有没有办法在使用 request.get 方法时将纪元日期转换为日期时间格式?

java - 将代码从 java 转换为 python

python-2.7 - PyInstaller 无法处理简单的 HelloWorld 程序

C++ - 读取 CSV 文件的列并仅保留以特定字符串开头的列

如果属性有多个值,同时复制其他值,则 Powershell 拆分 PSCustomObject

c++ - 在桌面上创建一个按钮