0

我想比较两个自变量如何随时间变化,方法是将它们都绘制在一张图上。所有三个变量都是数组的形式,我从一个文本文件中提取。这是我到目前为止所得到的:

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

问题是,它不起作用,我不知道为什么。我从一个关于绘制两个函数的教程中得到它。

4

2 回答 2

1

编辑:我认为问题可能在于您如何提取数据。当您调用A=f1andB=f2时,您应该编写A=f1(t)andB=f2(t)以符合您构造f1and的方式f2。然而,为什么要这样做呢?

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]

对于绘图,我更喜欢面向对象的方法。

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')
于 2013-07-11T16:33:36.830 回答
0

我们绘制数据而不是函数。所以通过AB是错误的。我认为你需要做的是:

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

我已经测试过您D的值是否正确,例如D = [list(range(100)), list(range(10, 110)), list(range(20, 120))]. 代码运行良好。

于 2013-07-11T16:29:22.713 回答