Created
October 7, 2019 23:57
-
-
Save AnandSingh/644386a0b965ae34769b50606e6545d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import time, random | |
import math | |
from collections import deque | |
from matplotlib.offsetbox import AnchoredText | |
from matplotlib import pyplot as plt | |
import numpy as np | |
import operator | |
import time | |
import os | |
#start = time.time() | |
class RealtimePlot: | |
def __init__(self, axes, c): | |
self.axis_x = []#deque(maxlen=max_entries) | |
self.axis_y = []#deque(maxlen=max_entries) | |
self.axes = axes | |
#self.max_entries = max_entries | |
self.lineplot, = axes.plot([], [], "o-", lw=0.4, ms=0.5, c=c) | |
self.axes.set_autoscaley_on(True) | |
def add(self, x, y): | |
self.axis_x.append(x) | |
self.axis_y.append(y) | |
self.lineplot.set_data(self.axis_x, self.axis_y) | |
#self.axes.set_xlim(self.axis_x[0], max(self.axis_x)) | |
self.axes.set_xlim(self.axis_x[0], self.axis_x[-1] + 1e-15) | |
max_idx, max_val_y = max(enumerate(self.axis_y), key=operator.itemgetter(1)) | |
max_val_x = self.axis_x[max_idx] | |
text = "MAX("+str(max_val_x)+","+str(max_val_y)+")" | |
anchored_text = AnchoredText(text, loc=4) | |
self.axes.add_artist(anchored_text) | |
#self.axes.set_xlim([min(self.axis_x), max(self.axis_x)]) | |
#self.axes.set_ylim([min(self.axis_y), max(self.axis_y)]) | |
self.axes.relim() | |
self.axes.autoscale_view() # rescale the y-axis | |
def animate(self, figure, callback, interval = 50): | |
import matplotlib.animation as animation | |
def wrapper(frame_index): | |
self.add(*callback(frame_index)) | |
self.axes.relim(); self.axes.autoscale_view() # rescale the y-axis | |
return self.lineplot | |
animation.FuncAnimation(figure, wrapper, interval=interval) | |
def main(): | |
fig, axes = plt.subplots() | |
cnt = 1 | |
#display = RealtimePlot(axes) | |
#display.animate(fig, lambda frame_index: (time.time() - start, random.random() * 100)) | |
display = RealtimePlot(axes, 'red') | |
while True: | |
# for genrating random number | |
#for x in range(1000): | |
# cnt = cnt +1 | |
# display.add(cnt, random.randint(1,101)) | |
# plt.pause(0.001) | |
# time.sleep(1) | |
# genrate a sine wave for fun | |
x = np.linspace(0, 2* np.pi, 60) | |
sinewave = np.sin(x) | |
cnt = cnt - 1 | |
for x in sinewave: | |
display.add(cnt, x) | |
plt.pause(0.001) | |
time.sleep(0.05) | |
cnt = cnt +1 | |
# to still show the graph when progrm ends | |
while True: | |
plt.pause(0.001) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment