繁体   English   中英

如何退出 python matplotlib 并在此之后继续代码

[英]How to exit python matplotlib and continue code after that

我的 python 项目有问题。 现在我正在使用 pyserial 为 Arduino 和 matplotlib 绘制实时图形。 我想将来自 Arduino 的温度传感器数据实时绘制成图形。 获得数据后,我想在关闭显示的图形后继续执行其他行代码。 在这种情况下,我想在关闭图形显示后打印“ok”。 这是我使用的代码:

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')

在这种情况下,我无法在关闭实时图形后打印“确定”。 即使我关闭它,它也会继续显示图表。 似乎他们一直在循环。 我找不到打破循环并继续下一行代码的方法。 如何打破这种情况的循环并继续打印“ok”。 希望任何人都可以帮助..

你必须使用 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)

在这种情况下,它会在任何键事件之后中断循环,您可以定义一个特定的键来中断循环或采取某些操作。

这个问题是关于鼠标点击事件,但你会发现更多有用的信息。

close event更适合您的任务。 由于plt.pasue()也会触发此事件,您可以使用其他命令来更新您的图形。

逻辑是:先画个图,不关闭。 在每次迭代中,您只需要更新数据并重新绘制它。 这比每次迭代中的显示/关闭图都快。

然而,如果你想让你的绘图与你的 COM3 事件同步仍然很困难,因为仍然会有延迟。

您可以参考Matplotlib / PyPlot 中的 Fast Live Plotting来加快更新速度。

这是我的演示:

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM