【发布时间】:2018-08-29 23:51:30
【问题描述】:
我需要绘制一些物体(汽车)的速度。
每个速度都通过例程计算并写入文件,大致通过这个(我删除了一些行以简化):
thefile_v= open('vels.txt','w')
for car in cars:
velocities.append(new_velocity)
if len(car.velocities) > 4:
try:
thefile_v.write("%s\n" %car.velocities) #write vels once we get 5 values
thefile_v.close
except:
print "Unexpected error:", sys.exc_info()[0]
raise
结果是一个文本文件,其中包含每辆车的速度列表。
类似这样的:
[0.0, 3.8, 4.5, 4.3, 2.1, 2.2, 0.0]
[0.0, 2.8, 4.0, 4.2, 2.2, 2.1, 0.0]
[0.0, 1.8, 4.2, 4.1, 2.3, 2.2, 0.0]
[0.0, 3.8, 4.4, 4.2, 2.4, 2.4, 0.0]
然后我想绘制每个速度
with open('vels.txt') as f:
lst = [line.rstrip() for line in f]
plt.plot(lst[1]) #lets plot the second line
plt.show()
这是我发现的。这些值被视为一个字符串并将它们作为 yLabel。
我解决了这个问题:
from numpy import array
y = np.fromstring( str(lst[1])[1:-1], dtype=np.float, sep=',' )
plt.plot(y)
plt.show()
我了解到,我之前构建的一组速度列表被视为数据行。
我必须将它们转换为数组才能绘制它们。然而,括号 [] 进入了方式。通过将数据行转换为字符串并通过此删除括号(即 [1:-1])。
它现在正在工作,但我确信有更好的方法来做到这一点。
有没有cmets?
【问题讨论】:
-
您使用的是 python 2.7 还是 3+?如果您使用 2.7,我建议使用 cPickle 导入将数组保存在 pickle 文件中。否则你可以看 3+ 的泡菜。我知道这不能回答您的问题,但它可以更轻松地从硬盘读取对象。
-
我使用 python 2.7
标签: python arrays string list matplotlib