我最近在学习如何使用matplotlib的python。我的目标是使用matplotlib通过读取文件(“somelog.log”)动态显示绘图。如果有新行添加到此日志文件,则更新反映到今天日期的条形图的总计数。
import matplotlib.pyplot as plt
import numpy as np
proddict = {}
prodlist = []
f = open ("somelog.log", 'r')
f.seek(0, os.SEEK_END) # read end of file
loop=True
while loop:
line = f.readline()
if not line: # if we don't get any data
time.sleep(0.1)
continue #retry
else:
with open ("somelog.log", 'r') as f:
for line in f:
matches = re.findall(r'(\d+[-]\d+[-]\d+)', line)
for match in matches:
count = proddict.get(match,0)
proddict[match] = count + 1
for k,v in proddict.iteritems():
prodlist.append((k,v))
prodlist = sorted(prodlist)
plt.ion()
W = np.arange(len(prodlist))
xs = []
ys = []
for x,y in prodlist:
xs.append(x)
ys.append(y)
plt.draw()
rects1 = plt.bar(W, ys, color='green', align= 'center')
for rect in rects1:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height),ha='center', va='bottom')
plt.draw()
plt.xticks(W, xs, rotation='vertical')
plt.title(' number of scripts executed (realtime)')
plt.xlabel('Date')
plt.ylabel('Usage')
plt.grid(True)
plt.ylim(0,500) # that's the limit
plt.legend(loc=0)
plt.show()
我得到的是结果:
我遇到的问题是:
当我第一次发出这个脚本时,它不会触发条形图,因为它正在等待新行添加到日志文件(“somelog.log”)。一旦检测到添加了新行,则触发绘图(如图中所附)。但是,当另一个新行添加到somelog.log时,它不会动态更新总计数。 (我希望最新日期的总数从129变为130)在此图片中显示
有人可以让我知道什么是错的吗?