Fra*_*nTo 4 python arrays string list matplotlib
我需要绘制一些物体(汽车)的速度。
每个速度都通过例程计算并写入文件中,大致如下(我删除了一些行以简化):
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
Run Code Online (Sandbox Code Playgroud)
其结果是一个文本文件,其中包含每辆车的速度列表。
像这样的东西:
[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]
Run Code Online (Sandbox Code Playgroud)
然后我想绘制每个速度
with open('vels.txt') as f:
lst = [line.rstrip() for line in f]
plt.plot(lst[1]) #lets plot the second line
plt.show()
Run Code Online (Sandbox Code Playgroud)
这就是我发现的。这些值被视为字符串并将它们作为 yLabel。

我通过这个得到了它的工作:
from numpy import array
y = np.fromstring( str(lst[1])[1:-1], dtype=np.float, sep=',' )
plt.plot(y)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我了解到,我之前构建的一组速度列表被视为数据行。
我必须将它们转换为数组才能绘制它们。然而,方括号 [] 妨碍了。通过将数据行转换为字符串并通过它删除括号(即[1:-1])。
它现在正在工作,但我确信有更好的方法来做到这一点。
任何意见?
只是说你有 array [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()
Run Code Online (Sandbox Code Playgroud)
如果您想要 x 轴有不同的间隔,那么:
interval_size = 2.4 #example interval size
xs = [x * interval_size for x in range(len(ys))]
Run Code Online (Sandbox Code Playgroud)
另外,当从文本文件读取值时,请确保已将值从字符串转换回整数。这可能是为什么您的代码假设您的输入是 y 标签。