我需要绘制一些物体(汽车)的速度。
每个速度都通过例程计算并写入文件中,大致如下(我删除了一些行以简化):
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])。
它现在正在工作,但我确信有更好的方法来做到这一点。
有什么意见吗?
最佳答案
假设您有数组[0.0, 3.8, 4.5, 4.3, 2.1, 2.2, 0.0]
,要绘制该数组,代码将类似于:
import matplotlib.pyplot as plt
ys = [0.0, 3.8, 4.5, 4.3, 2.1, 2.2, 0.0]
xs = [x for x in range(len(ys))]
plt.plot(xs, ys)
plt.show()
# Make sure to close the plt object once done
plt.close()
如果您希望 x 轴有不同的间隔,则:
interval_size = 2.4 #example interval size
xs = [x * interval_size for x in range(len(ys))]
此外从文本文件读取值时,请确保您已将值从字符串转换回整数。这也许就是为什么您的代码假设您的输入是 y 标签。
关于python - 在Python中绘制列表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49396526/