Matplotlib实时更新图 [英] Matplotlib Live Update Graph
本文介绍了Matplotlib实时更新图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是取自本网站的示例代码: http://pythonprogramming.net/python-matplotlib-live-updating-graphs/
Below is a sample code taken from this website: 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()
数据是逗号分隔的文本文件看起来像这样:
the data are comma delimited text file looks something like this:
DD/MM/YYYY H:M, 10.0, 20.0
DD/MM/YYYY H:M, 12.0, 22.0
这是它的外观片段,我的文件中有数千行这样的行.
This is a snippet of how it looks like, i got thousands of these lines in my file.
由于我有两条线图而不是一条线,我如何使上面的代码适合这里?
How can i make the code above to fit in here since i have two lines graph rather than one line ?
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()
推荐答案
首先,这是一个关于如何制作动画的非常糟糕的例子.
First, that is a really bad example of how to do animation.
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)
这篇关于Matplotlib实时更新图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文