Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotting data from a list in python

I need to plot the velocities of some objects(cars).

Each velocity are being calculated through a routine and written in a file, roughly through this ( I have deleted some lines to simplify):

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

The result of this is a text file with list of velocities for each car.

something like this:

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

Then I wanted to plot each velocity

with open('vels.txt') as f:
    lst = [line.rstrip() for line in f]

plt.plot(lst[1]) #lets plot the second line
plt.show()

This is what I found. The values are taken as a string and put them as yLabel.

enter image description here

I got it working through this:

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

What I learnt is that, the set of velocity lists I built previously were treated as lines of data.

I had to convert them to arrays to be able to plot them. However the brackets [] were getting into the way. By converting the line of data to string and removing the brackets through this (i.e. [1:-1]).

It is working now, but I'm sure there is a better way of doing this.

Any comments?

like image 482
FranTo Avatar asked Sep 03 '26 05:09

FranTo


1 Answers

Just say you had the array [0.0, 3.8, 4.5, 4.3, 2.1, 2.2, 0.0], to graph this the code would look something like:

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()

if you wanted to have different intervals for the x axis then:

interval_size = 2.4 #example interval size
xs = [x * interval_size for x in range(len(ys))]

Also when reading your values from the text file make sure that you have converted your values from strings back to integers. This maybe why your code is assuming your input is the y label.

like image 51
Max Collier Avatar answered Sep 04 '26 20:09

Max Collier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!