我正在尝试从表中读取最新行并在 python 中使用 animate 和 matplotlib 绘制图形。该表每 1 秒用一个新值更新一次。我需要通过实时绘制值来模拟图表。但是,当我使用间隔为 1 秒的 animate 函数时,每次获取间隔都会得到相同的值。
我正在添加代码供您参考。请让我知道我错过了什么。当我使用平面文件而不是 MySql 表时,相同的代码运行良好。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import mysql.connector
import pandas as pd
style.use('fivethirtyeight')
mydb = mysql.connector.connect(
host="xxxxxxxxxx",
user="xxxxx",
passwd="xxxxxxx",
database="sakila"
)
fig = plt.figure(figsize=(8,5))
ax = plt.subplot2grid((1,1), (0,0))
plt.ion()
cursor = mydb.cursor()
def animate(i):
df = pd.read_sql("SELECT * FROM DATA_TEST ORDER BY ID DESC LIMIT 1", mydb)
y = df["VALUE"]
x = df["ID"]
xs = []
ys = []
xs.append(x)
ys.append(float(y)*100)
ax.clear()
ax.plot(xs,ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
## TESTING CURSOR IN FOR LOOP
import mysql.connector
import pandas as pd
import time
mydb = mysql.connector.connect(
host="xxxxxxx",
user="xxxx",
passwd="xxxxxx",
database="xxxxx"
)
for i in range(10):
cursor = mydb.cursor()
cursor.execute("SELECT * FROM DATA_TEST ORDER BY ID DESC LIMIT 1")
result = cursor.fetchall()
print("Total rows are: ", len(result))
for j in result:
print(j[0])
print(j[1])
time.sleep(10)
cursor.close()