0

I am learning to plot live graphs using matplotlib, and so far have managed to read live data from serial port and plot it.

Following is my code:-

import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *

import binascii
import serial
import time

x = []
y = []
plt.ion()
cnt=0

z1baudrate = 9600
z1port = 'COM6'

z1serial = serial.Serial(port=z1port, baudrate=z1baudrate)
z1serial.timeout = 1

print (z1serial.is_open)

def makeFig():
    plt.ylim(0,150)
    plt.title('Live Data')
    plt.grid(True)
    plt.ylabel('Temperature')
    plt.plot(x, y, 'ro-', label='F')
    plt.legend(loc='upper left')

if z1serial.is_open:
    while True:
        size = z1serial.inWaiting()
        if size:
            data = z1serial.read(1)
            data = (ord(data))
            print (data)
            if data:
                cnt = cnt+1
                x.append(cnt)
                y.append(data)
                drawnow(makeFig)
                plt.pause(.000001)
                cnt=cnt+1
                if(cnt>50):
                  x.pop(0)
                  y.pop(0)
            z1serial.flushInput()
            z1serial.flushOutput()

        else:
            print ('no data')
        time.sleep(1)
else:
    print ('z1serial not open')

I want to two buttons on the live graph, Start and Stop

Pressing Stop button would stop the live plotting, leaving behind a blank graph.

Pressing Start button would start the live plotting again.

I referred to the link < Matplotlib Python: How to add panel button> but couldn't use it properly to add to my code.

How can I add the buttons to the live plot?

Thanks in advance!

sophros
  • 14,672
  • 11
  • 46
  • 75
Sandrocottus
  • 521
  • 3
  • 8
  • 31
  • 1
    I am not sure you are using the right tool. `matplotlib` is best for *static* plots. If you are looking for a _live_ plotting mechanism then you probably should check [`d3.js`](https://d3js.org/). – sophros Dec 12 '18 at 14:05
  • Thanks for the suggestion. Actually I am trying to do it using python (hence matplotlib). ***.js*** becomes an altogether different domain for me. Are you saying that a button cannot be added to the live plot? – Sandrocottus Dec 13 '18 at 05:46
  • 1
    Matplotlib can plot buttons, see [here](https://matplotlib.org/gallery/widgets/buttons.html). Matplotlib can also start or stop animations, see [here](https://stackoverflow.com/questions/16732379/stop-start-pause-in-python-matplotlib-animation). It is hence not too clear from the question at which point you're stuck. – ImportanceOfBeingErnest Dec 13 '18 at 13:18

0 Answers0