Matplotlib 实时更新图表

0 投票
1 回答
3432 浏览
提问于 2025-04-18 16:44

下面是从这个网站上拿到的示例代码: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 个回答

4

首先,这真的是一个非常糟糕的动画示例。

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)

撰写回答