gpt4 book ai didi

python - 如何使用 matplotlib 更新图形

转载 作者:行者123 更新时间:2023-11-29 03:30:09 25 4
gpt4 key购买 nike

我正在使用 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", 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,但没有得到正确的结果。有什么帮助吗?

最佳答案

文档对如何使用的解释有点简单功能动画。但是,有examples in thegallery和博客教程,例如 Jake Vanderplas'sSam Dolan's PDF .

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()

更改各种值或代码行,看看会发生什么。看看会发生什么您将 return [line] 更改为其他内容。如果你学习和玩这些示例,您可以了解各个部分如何组合在一起。

一旦你理解了这个例子,你应该能够修改它以适合你的目标。

如果您遇到问题,请发布您的代码并描述错误消息或你看到的不当行为。

一些提示:

  • 由于动画需要调用line.set_data,我不认为你可以使用 Pandas 的 df.plot()。事实上,我不确定 Pandas DataFrame 是否是在这里有用。将数据吸入列表或 NumPy 数组可能会更好并像上面那样将它们传递给 line.set,而不涉及 Pandas。

  • 打开与数据库的连接应该进行一次。 animate 获取叫了很多次。因此,最好定义 connc 以及 query —— 每次调用 animate 时不会改变的任何内容> --在 animate 之外,并将它们作为参数传回给 animate 通过fargs 参数。

关于python - 如何使用 matplotlib 更新图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com