Plotting data in a list in Python
I need to plot the speed of some object (car).
Each speed is calculated by a routine and written in a file, something like this (I’ve removed some lines for simplicity):
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 is a text file with a list of the speeds of each vehicle.
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 want to plot each speed
with open('vels.txt') as f:
lst = [line.rstrip() for line in f]
plt.plot(lst[1]) #lets plot the second line
plt.show()
Here’s what I found. These values are treated as a string and they are treated as yLabel.
I got it through this :
from numpy import array
y = np.fromstring( str(lst[1])[1:-1], dtype=np.float, sep=',' )
plt.plot(y)
plt.show()
I
learned that the speed list set I built earlier is considered a row of data.
I have to convert them to an array to plot them. However, square brackets [] get in the way. By converting rows of data to strings and removing parentheses (that is, [1:-1]) through this.
It works now, but I’m sure there is a better way to do it.
Any comments?
Solution
Suppose you have an array [0.0, 3.8, 4.5, 4.3, 2.1, 2.2, 0.0]
, to plot this code, the code looks like this:
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 want to set 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 a
text file, make sure that you have converted your values from a string back to an integer. This is perhaps why your code assumes that your input is a y tag.