How to update a graph using matplotlib
Question: I'm using Panda and matplotlib to draw graphs in Python. I would like a live
updating gaph. Here is my code:

    
    
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    import time
    import numpy as np
    import MySQLdb
    import pandas
    
    def animate():
    
        conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="sentiment_index", use_unicode=True, charset="utf8")
        c = conn.cursor()
        query = """ SELECT t_date , score FROM mytable where t_date BETWEEN Date_SUB(NOW(), Interval 2 DAY) AND NOW()"""
        c.execute(query)
        rows=c.fetchall()
        df = pandas.read_sql(query, conn, index_col=['t_date'])
    
        df.plot()
        plt.show()
    
    animate()
    

I thought about using FuncAnimation but didn't get the right result. Any help
please?


Answer: The documentation is a bit light on explanation of how to use FuncAnimation.
However, there are [examples in the
gallery](http://matplotlib.sourceforge.net/examples/index.html) and blog
tutorials, such as [Jake
Vanderplas's](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-
tutorial/) and [Sam Dolan's PDF](http://sam-
dolan.staff.shef.ac.uk/mas212/lectures/l5.pdf).

This example from Jake Vanderplas's tutorial is perhaps the "Hello World" of
matplotlib animation:

    
    
    from __future__ import division
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    def init():
        return [line]
    
    def animate(i, ax, line):
        x = np.linspace(0, 2*np.pi, N) + i/(N*2)
        ax.set_xlim(x.min(), x.max())
        line.set_data(x, np.sin(x))
        return [line]
    
    N = 100
    fig, ax = plt.subplots()
    line, = ax.plot([], [])
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    
    ani = animation.FuncAnimation(
        fig, animate, init_func=init, interval=0, frames=int(4*np.pi*N), 
        repeat=True, blit=True, fargs=[ax, line])
    plt.show()
    

Change various values or lines of code and see what happens. See what happens
if you change `return [line]` to something else. If you study and play with
these examples, you can learn how the pieces fit together.

Once you understand this example, you should be able to modify it to fit your
goal.

If you have trouble, post your code and describe what error message or
misbehavior you see.

Some tips:

  * Since animation requires calling `line.set_data`, I don't think you can use Pandas' `df.plot()`. In fact, I'm not sure if the Pandas DataFrame is useful here. You might be better off sucking the data into lists or NumPy arrays and passing those to `line.set` as above, without getting Pandas involved.

  * Opening a connection to the database should be done once. `animate` gets called many times. So it is better to define `conn` and `c` and `query` \-- anything that does not change with each call to `animate` \-- outside of `animate`, and pass them back as arguments to `animate` via the `fargs` parameter.

