2

I have a problem with my python project. Right now I'm doing a real-time graph plotting using pyserial for Arduino and matplotlib. I want to plot temperature sensor data from Arduino into a graph in real-time. after I got the data, I want to proceed with other lines code after close the graph displayed. In this situation, I want to print 'ok' after I close the graph display. Here is the code that I use :

import serial
import matplotlib.pyplot as plt
import time


plt.ion()
fig=plt.figure()   
i=0
x1=list()
y1=list()
isrun = True
ser = serial.Serial('COM3',9600)
i=0
ser.close()
ser.open()
run = True


while True:
    data1 = ser.readline()
    print(data1.decode())
    x1.append(i)
    y1.append(data1.decode())
    plt.plot(x1, y1)
    plt.title('Temperature')
    i += 1
    plt.pause(0.005)
    plt.show(block=False)
    # if plt.close() :
    #     run= False
    #     ser.close()
    #     break

print('ok')

In this case, I cannot print 'Ok' after close the real-time graph. It keeps on showing the graph even after I close it. It seems like they keep on doing the loop. I cannot find a way to break the loop and proceed with the next line code. How to break the loop for this case and proceed on the print 'ok'. Hope anyone can help..

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
DinJer
  • 21
  • 2
  • I believe this is a duplicated of: (https://stackoverflow.com/questions/58012313/pyplot-catch-windows-10-close-windows-event)[https://stackoverflow.com/questions/58012313/pyplot-catch-windows-10-close-windows-event] – Jorge Morgado Oct 04 '20 at 17:42
  • thanks jorge for your recomendation, but it seen like i cannot open the link, it said page not found – DinJer Oct 05 '20 at 23:03

2 Answers2

1

you have to catch a key press event using fig.canvas.mpl_connect()

fig = plt.figure()
keep_ploting = True

def on_key(event):
    global keep_ploting 
    keep_ploting = False

while keep_ploting:
    data1 = ser.readline()
    print(data1.decode())
    x1.append(i)
    y1.append(data1.decode())
    plt.plot(x1, y1)
    plt.title('Temperature')
    i += 1
    plt.pause(0.005)
    plt.show(block=False)
    
    fig.canvas.mpl_connect('key_press_event', on_key)

in this case it's breaking the loop after any key event, you can define a specif key to break the loop or to take some action.

this question is about mouse click events but you will find further useful information.

tatarana
  • 198
  • 1
  • 8
0

The close event is more suitable for your task. As plt.pasue() also triggers this event, you can use other commands to update your figure.

The logic is: first draw a plot and do not close it. In every iteration you just need to update the data and re-draw it. This is faster than show/close figure in every iteration.

However, it is still hard if you want to make your plotting synchronized with your COM3 event since there will still be a delay.

You may refer to Fast Live Plotting in Matplotlib / PyPlot to make the updating even faster.

Here is my demo:

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

close_flag = 0

x = np.arange(0, 10)
y = np.arange(0, 10)

# to handle close event.
def handle_close(evt):
    global close_flag # should be global variable to change the outside close_flag.
    close_flag = 1
    print('Closed Figure!')


plt.ion()
fig, ax = plt.subplots()
fig.canvas.mpl_connect('close_event', handle_close) # listen to close event
line, = plt.plot(x, y)

t = 0
delta_t = 0.1
while close_flag == 0:
    if abs(t - round(t)) < 1e-5:
        print(round(t))
    
    x = x + delta_t
    y = y - delta_t
    line.set_data(x, y) # change the data in the line.
    
    ax.relim() # recompute the axes limits.
    ax.autoscale_view() # update the axes limits.
    
    fig.canvas.draw() # draw the figure
    fig.canvas.flush_events() # flush the GUI events for the figure.
    # plt.show(block=False)
    time.sleep(delta_t) # wait a little bit of time
    
    t += delta_t
    
    if close_flag == 1:
        break

print('ok')
dull-bird
  • 41
  • 3
  • Thanks dull-bird for your help. i will try to go and see for your recomendation on the fast plotting graph. – DinJer Oct 05 '20 at 23:22