Search code examples
pythonmatplotlibdrawnow

matplotlib not responding after a interactive plotting


I was working on a project using Arduino with python, I was plotting real-time sensor data from Arduino using libraries(pyfirmata,matplot,draw now) I am getting the real-time output but after the fixed iteration the figure got not responding. I attached the code below

import pyfirmata
import time
import matplotlib.pyplot as plt
from drawnow import *
import sys
board = pyfirmata.Arduino('COM8')
iter8 = pyfirmata.util.Iterator(board)
iter8.start()

LED = board.get_pin('d:13:o')
ldr=board.get_pin('a:0:o')
val=0
converted=1023
converted2=5.0/1023.0
s=[]
i=0

def makeFig():

    plt.figure(1)
    plt.ion()
    plt.plot(s)
    plt.title('My Live Streaming Sensor Data')  # Plot the title
    plt.grid(True)

while(i<=50):

    time.sleep(0.01)
    val=ldr.read()
    print(val * converted * converted2)
    s.append(val)
    i=i+1
    drawnow(makeFig)  # Call drawnow to update our live graph
    plt.pause(.000001)
plt.show()

I want to save the sensor plotting after some iteration that is my ultimate goal


Solution

  • You probably want to call plt.ioff() before plt.show().

    More generally, better work completely inside the event loop as shown below.

    import pyfirmata
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    
    board = pyfirmata.Arduino('COM8')
    iter8 = pyfirmata.util.Iterator(board)
    iter8.start()
    
    LED = board.get_pin('d:13:o')
    ldr=board.get_pin('a:0:o')
    val=0
    converted=1023
    converted2=5.0/1023.0
    s=[]
    i=0
    
    fig, ax = plt.subplots()
    line,= ax.plot([],[])
    
    def update(i):
    
        val=ldr.read()
        print(val * converted * converted2)
        s.append(val)
        line.set_data(range(len(s)), s)
        ax.autoscale()
        ax.relim()
        ax.autoscale_view()
    
    FuncAnimation(fig, update, frames=50, repeat=False)
    
    plt.show()