Search code examples
pythonmatplotlibplotgraphing

Plotting 2 arrays against another on one graph


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.


Solution

  • 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.