【发布时间】:2021-07-01 20:09:55
【问题描述】:
这段代码用于制作动画图表。 var xd 和 yd 是 x 轴和 y 轴的数据。所以我通过 +1 对 xd 进行了自动化处理,每 1 秒重复一次使用线程。不幸的是,结果是一个错误:'UnboundLocalError: local variable 'xd' referenced before assignment'。我尝试了很多答案,但有些结果是“定义 xd”或“语法错误”。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from time import sleep
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
xd = 0
def animate(i):
graph_data = open('Example.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(float(x))
ys.append(float(y))
ax1.clear()
ax1.plot(xs, ys)
def plotit():
threading.Timer(1.0, plotit).start()
xd += 1
yd = 1
data = open('/home/pi/Desktop/Real-Time car collision detection/Example.txt','a')
data.write(str(xd)+','+str(yd))
data.close()
//^ This line results with error
plotit()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()```
【问题讨论】:
标签: python multithreading matplotlib write