Matplotlib实时更新图

时间:2014-08-10 10:58:47

标签: python matplotlib

以下是从本网站获取的示例代码: http://pythonprogramming.net/python-matplotlib-live-updating-graphs/

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

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

def animate(i):
    pullData = open("sampleText.txt","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax1.clear()
    ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

数据是以逗号分隔的文本文件,如下所示:

 DD/MM/YYYY H:M, 10.0, 20.0
 DD/MM/YYYY H:M, 12.0, 22.0

这是它的样子片段,我的文件中有数千条这样的行。

如何使上面的代码适合这里,因为我有两行图而不是一行?

linematchregex = re.compile('(\d+/\d+/\d+ \d+:\d+),(\d+\.\d+)')

startTime = datetime.strptime(raw_input('please enter start time :'), '%d/%m/%Y %H:%M')
endTime   = datetime.strptime(raw_input('please enter end time :') , '%d/%m/%Y %H:%M')

with open(r'sample.txt', 'r') as strm:
    strm.next()
    t, y, temp = zip(*[p for line in strm for p in linematchregex.findall(line)])
t = [datetime.strptime(x, '%d/%m/%Y %H:%M') for x in t ]
y = [float(x) for i,x in enumerate(y) if startTime<=t[i]<=endTime]
temp = [float(x) for i,x in enumerate(temp) if startTime<=t[i]<=endTime]

t = [x for x in t if startTime<=x<=endTime]
fig = plt.figure()
fig.subplots_adjust(top=0.80)
ax1 = fig.add_subplot(1, 1, 1, axisbg='white')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax2 = ax1.twinx()
ax1.plot(t, y, 'c', linewidth=3.3)
ax2.plot(t, temp, linewidth=3.3)

plt.show()

1 个答案:

答案 0 :(得分:3)

首先,这是一个如何做动画的真的坏例子。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

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

ln1, = ax1.plot([], [], 'r-')
ln2, = ax1.plot([], [], 'g-')
def animate(i):
    # do what ever you need to get your data out
    # assume that you have x1, y1, x2, y2
    ln1.set_data(x1, y1)
    ln2.set_data(x2, y2)
    return ln1, ln2

ani = animation.FuncAnimation(fig, animate, interval=1000)