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!

3
  • 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. Commented Dec 12, 2018 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? Commented Dec 13, 2018 at 5:46
  • 1
    Matplotlib can plot buttons, see here. Matplotlib can also start or stop animations, see here. It is hence not too clear from the question at which point you're stuck. Commented Dec 13, 2018 at 13:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.