plot.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python3
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4. from matplotlib import style
  5. import numpy as np
  6. import random
  7. import serial
  8. #initialize serial port
  9. ser = serial.Serial()
  10. ser.port = '/dev/ttyS3' #Arduino serial port
  11. ser.baudrate = 115200
  12. ser.timeout = 10 #specify timeout when using readline()
  13. ser.open()
  14. if ser.is_open==True:
  15. print("\nAll right, serial port now open. Configuration:\n")
  16. print(ser, "\n") #print serial parameters
  17. # Create figure for plotting
  18. fig = plt.figure()
  19. ax = fig.add_subplot(1, 1, 1)
  20. xs = [] #store trials here (n)
  21. ys = [] #store relative frequency here
  22. rs = [] #for theoretical probability
  23. # This function is called periodically from FuncAnimation
  24. def animate(i, xs, ys):
  25. #Aquire and parse data from serial port
  26. line=ser.readline() #ascii
  27. line_as_list = line.split(b',')
  28. i = int(line_as_list[0])
  29. relProb = line_as_list[1]
  30. relProb_as_list = relProb.split(b'\n')
  31. relProb_float = float(relProb_as_list[0])
  32. # Add x and y to lists
  33. xs.append(i)
  34. ys.append(relProb_float)
  35. rs.append(0.5)
  36. # Limit x and y lists to 20 items
  37. #xs = xs[-20:]
  38. #ys = ys[-20:]
  39. # Draw x and y lists
  40. ax.clear()
  41. ax.plot(xs, ys, label="Experimental Probability")
  42. ax.plot(xs, rs, label="Theoretical Probability")
  43. # Format plot
  44. plt.xticks(rotation=45, ha='right')
  45. plt.subplots_adjust(bottom=0.30)
  46. plt.title('This is how I roll...')
  47. plt.ylabel('Relative frequency')
  48. plt.legend()
  49. plt.axis([1, None, 0, 1.1]) #Use for arbitrary number of trials
  50. #plt.axis([1, 100, 0, 1.1]) #Use for 100 trial demo
  51. # Set up plot to call animate() function periodically
  52. ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000)
  53. plt.show()