值未在字典中正确附加

时间:2018-01-20 01:48:21

标签: python matplotlib graph

我试图使用matplotlib随着时间的推移绘制一些随机数字,但似乎无法让它工作。图形的轴像我认为的那样移动,但没有图形线出现。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import *

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def yaxis():
    yvalue = randint(1,10)
    return yvalue

def animate(i):
    ys = []
    xs = []
    yvalue = yaxis()
    global xvalue
    xvalue += 1
    ys.append(yvalue)
    xs.append(xvalue)
    ax1.clear()
    ax1.plot(xs, ys)

xvalue = 0
ani = animation.FuncAnimation(fig, animate, interval=10)
plt.show()

我错过了什么?如果我打印出ys或xs字典,它们只显示一个值

1 个答案:

答案 0 :(得分:1)

您不应重新初始化动画内的 xs ys 列表。目前,每个列表只包含一个值。 这样的事情应该有效:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import *

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def yaxis():
    yvalue = randint(1,10)
    return yvalue

def animate(i):
    global xvalue, xs, ys
    yvalue = yaxis()
    xvalue += 1
    print(xvalue, yvalue)
    # append to the full lists
    ys.append(yvalue)
    xs.append(xvalue)
    ax1.clear()
    ax1.plot(xs, ys)

xvalue = 0
# Initialize outside the function
ys = []
xs = []
ani = animation.FuncAnimation(fig, animate, interval=30)
plt.show()

希望这对你的努力有所帮助。