Reputation: 13
I want to compare how two independent variables vary with time, by plotting both of them on the one graph. All three variables are in the form of arrays, which I pulled from a text file. This is what I have got so far:
from pylab import *
data_ = []
with open('all_the_data.txt') as dat_:
for line in dat_:
data_.append([i for i in line.split()])
D = zip(*data_)
def f1(t):
y = D[1]
return y
def f2(t):
y = D[2]
return y
if __name__ == '__main__':
t = D[0]
A = f1
B = f2
plot(t, A, 'bo')
hold('on')
plot(t, B, 'gX')
xlabel('timestamp (unix)')
ylabel('Station population')
legend('Station 1','Station 2')
title('Variance of Stations 1 and 2')
show()
savefig('2_stations_vs_time.png')
Problem is, it isn't working, and i don't know why. I got it from a tutorial on graphing two functions.
Upvotes: 1
Views: 8249
Reputation: 18521
Edit: I think the problem may be with how you extract the data. When you call A=f1
and B=f2
, you should write A=f1(t)
and B=f2(t)
to conform with the way you've constructed f1
and f2
. However, why do it that way?
with open('all_the_data.txt', 'r') as dat_:
for line in dat_:
data_.append([i for i in line.strip().split()])
D = zip(*data_)
t = D[0]
A = D[1]
B = D[2]
For plotting, I prefer the object oriented approach.
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.plot(t, A, 'bo', label="Station 1")
ax.plot(t, B, 'gX', label="station 2")
ax.legend()
ax.set_xlabel('timestamp (unix)')
ax.set_ylabel('Station population')
ax.set_title('Variance of Stations 1 and 2')
f.savefig('2_stations_vs_time.png')
Upvotes: 1
Reputation: 8610
We plot the data not the function. So pass A
, B
is wrong. I think what you need to do is:
from pylab import *
data_ = []
with open('all_the_data.txt') as dat_:
for line in dat_:
data_.append([i for i in line.split()])
D = zip(*data_)
if __name__ == '__main__':
t = D[0]
A = D[1]
B = D[2]
plot(t, A, 'bo')
hold('on')
plot(t, B, 'gX')
xlabel('timestamp (unix)')
ylabel('Station population')
legend('Station 1','Station 2')
title('Variance of Stations 1 and 2')
show()
savefig('2_stations_vs_time.png')
I have tested if your D
is a right value, for example D = [list(range(100)), list(range(10, 110)), list(range(20, 120))]
. The code works well.
Upvotes: 0