python - 在Python中绘制列表中的数据

标签 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

结果是一个文本文件,其中包含每辆车的速度列表。

像这样:

[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。

enter image description here

我通过这个工作了:

from numpy import array

y = np.fromstring( str(lst[1])[1:-1], dtype=np.float, sep=',' )
plt.plot(y)
plt.show()

enter image description here

我了解到,我之前构建的一组速度列表被视为数据行。

我必须将它们转换为数组才能绘制它们。然而,方括号 [] 妨碍了。通过将数据行转换为字符串并通过此删除括号(即 [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/

相关文章:

c - 如何动态分配二维结构数组?

c++ - 在不先构建数组的情况下将数字列表传递给 C++ 中的函数?

c - 如何从文件中扫描字符串并将其存储在字符串数组(二维数组)中?

java - 将字符串转换为适当的数据类型

javascript - Javascript 中带有通配符/Min、MaxLength 的字符串正则表达式包含数字

python - 使用 BeautifulSoup 抓取 Google 搜索

python - 将 Pandas Data Frames 存储在字典中或面板中更好?

python - 使用多列条件过滤,Python 3.6

python - 使用 OpenCV python 查看原始 10 位 USB 相机

javascript - 从长绳子中取出一段绳子