Search code examples
pythongraphlinegraph

How to create a simple line graph in Python


Can someone please tell me if there is a way of making a constantly updating line graph in Python? Thanks for any answers.


Solution

  • First of all you will need to install some dependencies: matplotlib and numpy.

    The first option is to use matplotlib animation like in this example:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    
    def update_line(num, data, line):
        line.set_data(data[..., :num])
        return line,
    
    fig1 = plt.figure()
    
    data = np.random.rand(2, 25)
    l, = plt.plot([], [], 'r-')
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    plt.xlabel('x')
    plt.title('test')
    line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data,l),interval=50, blit=True)
    plt.show()
    

    A more mathematical option is this one:

    import matplotlib.pyplot as plt
    import numpy as np
    import time 
    
    x = np.linspace(0, 1, 20)
    y = np.random.rand(1, 20)[0]
    
    
    plt.ion()
    fig = plt.figure()
    ay = fig.add_subplot(111)
    line1, = ay.plot(x, y, 'b-') 
    
    for i in range(0,100):
        y = np.random.rand(1, 20)[0]
        line1.set_ydata(y)
        fig.canvas.draw()
        time.sleep(0.1)
    

    I hope this is what you were searching for.