matplotlib动画不起作用

时间:2016-08-10 11:43:10

标签: python matplotlib

我编写了这段代码,用于使用matplotlib绘制动态图,但它不起作用:

from matplotlib import style
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data = open ('data.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
    if len(line) > 1:
        x, y = line.split(',')
        # print(x,y)
        xs.append(x)
        ys.append(y)
# print(xs,ys)
# ax1.clear()
ax1.plot(xs, ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)

data.txt数据如下:

1,0.8
2,1.4
3,1.4
4,2.6
5,1.5
6,1.6
7,2.4

我使用python2.7和最新版本的matplotlib

1 个答案:

答案 0 :(得分:0)

你需要在animate中设置ax1.plot。

def animate(i):
   graph_data = open ('data.txt','r').read()
   lines = graph_data.split('\n')
   xs = []
   ys = []
   for line in lines:
      if len(line) > 1:
      x, y = line.split(',')
      xs.append(x)
      ys.append(y)
   ax1.plot(xs, ys)

这样写的时候,它可以在我的机器上运行。