title: Animating plots conditionally in Python
body: <p>This is my first post here.</p>
  <p>I was trying to plot some serial data(temperature), the data printed by my microcontroller in the following format: temperature data is printed every 1 seconds and otherwise some other data is printed(like output from different sensors).</p>
  <p>My implementation so far is that in order for Python to know that the data we are sending is the temperature data, I send a unique code like say &quot;kkk1k1&quot; and the temperature data in the next line.</p>
  <p>Then I can read the serial port in Python and check whether the serial data is the unique code and when it matches, read the next line and then plot it. Otherwise skip plotting and and keep reading.</p>
  <p>When I try this the chart doesn't show anything and it hangs.</p>
  <p>Does anyone know how to update my plot only when a certain condition is fulfilled?
  Any links to documentation regarding this will be appreciated.</p>
  <p>Thank You</p>
  <p>Note: This query is resolved. I am writing it here as do not know how to do it otherwise.</p>
  <p>This is my implementation, if you find any errors please let me know. Thanks!</p>
  <pre><code>import numpy as np
  import matplotlib.pyplot as plt
  import matplotlib.animation as animation
  import sys, time, math, serial
  
  xsize=100
  #These are used to display current temp, max and min temp
  curr_temp = 0.0
  ma = 0
  mi = 0 
  
  
  def data_gen():
      global ma, mi
      t = data_gen.t
      while True:
         #Since lots of different data is being printed from the serial, we 
         #need our script to different what useful for it
         #so that when the temperature data comes, it only plots that.
         #Here the scripts continuously check for serial input, in our main 
         #code, we send a key before sending the temperature data
         #Script reads the serial line and matches it with the key. If match 
         #successful, it immediate read next line and then proceed to plot 
         #it. Otherwise If match is not successful, it keeps reading and the 
         #Realtime plot pauses.
         strin = ser.readline()
         strr = strin.decode() 
         key = b'10011\r\n'
         key = key.decode()
         if (strr == key):
          #first update t and then get the values.
          t+=1
          print ('HOORAY')
          strin = ser.readline()
          print (strin.decode('utf-8'))
          val = float(strin)
          #here basically we check if the the current temperature is maximum 
          #or minimum.
          #at start, we initialize the max and min values 
          if t == 5:
              ma = val
              mi = val
          else:
              if ma &lt; val:
                  ma = val
              if mi &gt; val:
                  mi = val
          #give the plot functions the following data to plot.
          yield t, val, ma, mi
     
  def run(data):
      # update the data
      t,y, maxx, minn = data
      if t&gt;-1:
          xdata.append(t)
          ydata.append(y)
          if t&gt;xsize: # Scroll to the left.
              ax.set_xlim(t-xsize, t)
          line.set_data(xdata, ydata)
          #now update the text_boxes 
          TEMP1.set_text(y)
          TEMPMa.set_text(maxx)
          TEMPMi.set_text(minn)  
      return line
  
  def on_close_figure(event):
      sys.exit(0)
  
  # configure the serial port
  ser = serial.Serial(
      port='COM3', # Change as needed
      baudrate=115200,
      parity=serial.PARITY_NONE,
      stopbits=serial.STOPBITS_TWO,
      bytesize=serial.EIGHTBITS,
      timeout=1
  )
  ser.isOpen()
  
  data_gen.t = -1
  fig = plt.figure()
  fig.canvas.mpl_connect('close_event', on_close_figure)
  ax = fig.add_subplot(111)
  
  #Differentiating each line from one another.
  line, = ax.plot([], [], lw=2, color=&quot;red&quot;)
  ax.set_ylim(15, 45)
  ax.set_xlim(0, xsize)
  
  #Axis lables and text_boxes
  plt.xlabel('Time')
  plt.ylabel('Measurement Temperature')
  fig.text(0.91,0.80, 'TEMP', fontweight = 'bold', size = 10)
  fig.text(0.91,0.65, 'MAX', fontweight = 'bold', size = 10)
  fig.text(0.91,0.50, 'MIN', fontweight = 'bold', size = 10)
  TEMP1 = fig.text(0.91,0.75, curr_temp)
  TEMPMa = fig.text(0.91,0.60, curr_temp)
  TEMPMi = fig.text(0.91,0.45, curr_temp)
  ax.grid()
  xdata, ydata = [], []
  
  # Important: Although blit=True makes graphing faster, we need blit=False 
  #to prevent spurious lines to appear when resizing the stripchart.
  ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10, 
  repeat=False)
  plt.show()
  </code></pre>