'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?



Solution 1:[1]

The example is not complete, so some assumptions must be made here. In general, use numpy or pandas to store your data.

Suppose car is an object, with a velocity attribute, you can write all velocities in a list, save this list as text file with numpy, read it again with numpy and plot it.

import numpy as np
import matplotlib.pyplot as plt

class Car():
    def __init__(self):
        self.velocity = np.random.rand(5)

cars = [Car() for _ in range(5)]
velocities = [car.velocity for car in cars]
np.savetxt("vels.txt", np.array(velocities))

#### 

vels = np.loadtxt("vels.txt")
plt.plot(vels.T)
## or plot only the first velocity
#plt.plot(vels[0]

plt.show()

enter image description here

Solution 2:[2]

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.

Solution 3:[3]

Just one possible easy solution. Use the map function. Say in your file, you have the data stored like, without any [ and ] non-convertible letters.

#file_name: test_example.txt
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 the next step is;

import matplotlib.pyplot as plt

path = r'VAR_DIRECTORY/test_example.txt' #the full path of the file


with open(path,'rt') as f:
    ltmp = [list(map(float,line.split(','))) for line in f]

plt.plot(ltmp[1],'r-')
plt.show()

In top, I just assume you want to plot the second line, 0.0, 2.8, 4.0, 4.2, 2.2, 2.1, 0.0. Then here is the result. enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ImportanceOfBeingErnest
Solution 2 Rahul Madan
Solution 3