Skip to content

Instantly share code, notes, and snippets.

@nanounanue
Forked from sbourdelin/rt-draw.py
Created September 4, 2019 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanounanue/b228a0eea36a5a0dd9e57d065abe44fc to your computer and use it in GitHub Desktop.
Save nanounanue/b228a0eea36a5a0dd9e57d065abe44fc to your computer and use it in GitHub Desktop.
Draw plot in real time with matplotlib
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Savoir-Faire Linux Inc.
# Authors:
# Sebastien Bourdelin <sebastien.bourdelin@savoirfairelinux.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys, argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import re
# The update graph function
def animate(data):
global x_max, x_min, x, y
try:
# we must recalculate the abscissa range
x_new = float(data)
if x_max is None or x_new > x_max:
x_max = x_new
if x_min is None or x_new < x_min:
x_min = x_new
ax.set_xlim(x_min, x_max)
# add the new plot coordinate
x.append(x_new)
y.append(0)
line.set_data(x, y)
return line,
except KeyboardInterrupt:
print("leaving...")
# The data generator take its
# input from file or stdin
def data_gen():
while True:
line = fd.readline().strip()
if line:
yield line
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--file', dest='filename')
args = parser.parse_args()
if args.filename:
fd = open(args.filename, encoding='utf-8')
else:
fd = sys.stdin
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], 'ro')
x_min = x_max = None
x = []
y = []
ax.set_ylim(-1, 1)
anim = animation.FuncAnimation(fig, animate, frames=data_gen, repeat=False)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment