import matplotlib.pyplot as plt import matplotlib.animation as animate import math, json, traceback try: import matplotlib matplotlib.use("WXAgg") # to force use one of the matplot's UI backend instead of an IDE's choice except ImportError: traceback.print_exc() def plotter(): a = json.load(open('settings.json', 'r')) sensors = len(a['sensor_ports']) windowsize = a['winSize'] delay = a["delay"] / 1000 file = open(a["file_name"], "r") colors = ['blue', 'orange', 'green', 'yellow'] fig, axs = plt.subplots(1, 1) timeStamps = [] sensorsData = [] i = 0 while i <= sensors: sensorsData.append([]) i = i + 1 def animation(t): next_line = file.readline() if next_line: line = next_line.split(',') if len(line) >= sensors: i = 1 timeStamps.append(line[0]) # get rid of the zeroth value if it exceeds pre-defined window size if windowsize != 0 and len(timeStamps) > windowsize: timeStamps.pop(0) val_lists = [] while i <= sensors: if not line[i]: # pass on invalid values continue sensorsData[i - 1].append(float(line[i])) # cast it to float so the y-axis will not jump around # get rid of the zeroth value if it exceeds pre-defined window size if windowsize != 0 and len(sensorsData[i - 1]) > windowsize: sensorsData[i - 1].pop(0) val_lists.append(sensorsData[i - 1]) i += 1 for j in range(len(val_lists)): axs.plot(timeStamps, val_lists[j], color=colors[j], label=f'sensor {j + 1}') # TODO: display sensor number to the actual arduino's port & # axs.annotate('%0.2f' % val_lists[j][-1], xy=(1, val_lists[j][-1]), xytext=(8, 0), # xycoords=('axes fraction', 'data'), textcoords='offset points') # Acknowledgement: https://stackoverflow.com/a/13589144 handles, labels = plt.gca().get_legend_handles_labels() by_label = dict(zip(labels, handles)) axs.legend(by_label.values(), by_label.keys(), loc='best') print(by_label.items()) return animate.FuncAnimation(plt.gcf(), func=animation) # , interval=delay * 500) # ani.save("plot.gif") # plt.ion() # plt.show(block=True) # plotter()