python - How to update a graph using matplotlib -


i'm using panda , matplotlib draw graphs in python. live updating gaph. here code:

import matplotlib.pyplot plt import matplotlib.animation animation import time import numpy 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 mytable t_date between date_sub(now(), interval 2 day) , now()"""     c.execute(query)     rows=c.fetchall()     df = pandas.read_sql(query, conn, index_col=['t_date'])      df.plot()     plt.show()  animate() 

i thought using funcanimation didn't right result. please?

the documentation bit light on explanation of how use funcanimation. however, there examples in gallery , blog tutorials, such jake vanderplas's , sam dolan's pdf.

this example jake vanderplas's tutorial perhaps "hello world" of matplotlib animation:

from __future__ import division import numpy np import matplotlib.pyplot plt import matplotlib.animation 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 , see happens. see happens if change return [line] else. if study , play these examples, can learn how pieces fit together.

once understand example, should able modify fit goal.

if have trouble, post code , describe error message or misbehavior see.

some tips:

  • since animation requires calling line.set_data, don't think can use pandas' df.plot(). in fact, i'm not sure if pandas dataframe useful here. might better off sucking data lists or numpy arrays , passing line.set above, without getting pandas involved.

  • opening connection database should done once. animate gets called many times. better define conn , c , query -- not change each call animate -- outside of animate, , pass them arguments animate via fargs parameter.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -