Python 如何使用matplotlib更新图形
我正在使用Panda和matplotlib用Python绘制图形。 我想要一个实时更新的gaph。这是我的密码:Python 如何使用matplotlib更新图形,python,mysql,python-2.7,pandas,matplotlib,Python,Mysql,Python 2.7,Pandas,Matplotlib,我正在使用Panda和matplotlib用Python绘制图形。 我想要一个实时更新的gaph。这是我的密码: 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"
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()
我曾想过使用FuncAnimation,但没有得到正确的结果。有什么帮助吗?文档中对如何使用的解释有点浅显 动画。然而,也有一些网站和博客 教程,如和 Jake Vanderplas教程中的这个例子可能就是 matplotlib动画:
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()
更改不同的值或代码行,看看会发生什么。看看如果
您可以将返回[line]
更改为其他内容。如果你学习和玩这些
通过示例,您可以了解各个部分是如何组合在一起的
一旦您理解了这个示例,您应该能够修改它以适合您的需要
进球
如果您遇到问题,请发布您的代码,并描述错误消息或错误
你看,行为不端
一些提示:
- 由于动画需要调用
,我认为您不需要 可以使用Pandas'line.set_data
。事实上,我不确定熊猫数据帧是否正确 这里有用。您最好将数据吸入列表或NumPy数组中 并将它们传递到df.plot()
行。如上所述设置
,而不涉及熊猫
- 打开与数据库的连接应该只打开一次<代码>动画获取
我打了很多次电话。因此,最好定义
和conn
以及c
——每次调用query
,都不会改变的任何内容 在animate
之外,并通过动画
参数fargs