# Can you graph in real time in python?

3

I've been trying to get a graph in real time with matplotlib but it's almost impossible, is there any way I can do this?

The issue is that I am receiving data through the usb port and I am storing them in a list, which is increasing as there is new data. What I want is that as a new data is received (which is very very fast) it will be shown in a graph in real time.

I tried like this but it did not work:

``````import matplotlib.pyplot as plt
import analog

b = analog('COM3')
g = []

while (True):
val = b.analogRead(pin)
res = int((int(val) * 250000) / 1023)
g.append(res)
print("%s ............... %s" % (res, t))
plt.figure(1)
plt.plot(g)
plt.show(block = False)

plt.close('all')
``````

asked by Michael Lan 22.04.2016 в 21:55
source

## 2 answers

4

The following should work although it does not have to have a great performance. If you are going to make a graph every second, if you need something that draws more graphs per second you can look to optimize this code (but it will be a bit more complex) or you can use PyQwt. The simple code in matplotlib would be:

``````import numpy as np
import matplotlib.pyplot as plt

plt.ion() # decimos de forma explícita que sea interactivo

y = [] # los datos que vamos a dibujar y a actualizar

# el bucle infinito que irá dibujando
while True:
y.append(np.random.randn(1)) # añadimos un valor aleatorio a la lista 'y'

# Estas condiciones las he incluido solo para dibujar los últimos
# 10 datos de la lista 'y' ya que quiero que en el gráfico se
# vea la evolución de los últimos datos
if len(y) <= 10:
plt.plot(y)
else:
plt.plot(y[-10:])

plt.pause(0.05) # esto pausará el gráfico
plt.cla() # esto limpia la información del axis (el área blanca donde
# se pintan las cosas.
``````

answered by 24.04.2016 в 09:50
-1

Another interesting option is PyQtGraph which is written in Python and uses PyQt4 / PySide for the graphic part and NumPy for the calculation.

One thing that surprised me is that you can interact with the graphic in real time with the mouse (including with 3D graphics ).

answered by 27.11.2016 в 11:35