【发布时间】:2019-02-20 09:19:49
【问题描述】:
以下是取自本网站的示例代码: 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()
【问题讨论】:
标签: python matplotlib