Last active
December 1, 2019 21:08
-
-
Save benjaminalt/738b453fdefc27595304540cca28d458 to your computer and use it in GitHub Desktop.
Real-time plotting with matplotlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import time | |
| import multiprocessing as mp | |
| from queue import Empty | |
| class PlotterProcess(mp.Process): | |
| def __init__(self, queue, series_labels, shutdown_event, output_filename): | |
| super(PlotterProcess, self).__init__() | |
| self.queue = queue | |
| self.shutdown_event = shutdown_event | |
| self.fig = plt.figure() | |
| self.ax1 = self.fig.add_subplot(1,1,1) | |
| self.xs = [[] for _ in range(len(series_labels))] | |
| self.ys = [[] for _ in range(len(series_labels))] | |
| self.ax1.legend(series_labels) | |
| self.series_labels = series_labels | |
| self.output_filename = output_filename | |
| def run(self): | |
| while not self.shutdown_event.is_set(): | |
| try: | |
| series_idx, x, y = self.queue.get(block=True, timeout=3) | |
| self.xs[series_idx].append(x) | |
| self.ys[series_idx].append(y) | |
| self.redraw() | |
| except Empty: | |
| continue | |
| self.fig.savefig(self.output_filename) | |
| print("Plotter process exiting.") | |
| def redraw(self): | |
| self.ax1.clear() | |
| for series_idx in range(len(self.series_labels)): | |
| self.ax1.plot(self.xs[series_idx], self.ys[series_idx]) | |
| self.ax1.legend(self.series_labels) | |
| plt.draw() | |
| plt.pause(0.0001) | |
| class RealTimePlotter(object): | |
| def __init__(self, series_labels, output_filename): | |
| self.shutdown_event = mp.Event() | |
| self.queue = mp.Queue() | |
| self.plotter_process = PlotterProcess(self.queue, series_labels, self.shutdown_event, output_filename) | |
| def update(self, series_idx, x, y): | |
| self.queue.put((series_idx, x, y)) | |
| def start(self): | |
| self.plotter_process.start() | |
| def stop(self): | |
| self.shutdown_event.set() | |
| self.plotter_process.join() | |
| def __enter__(self): | |
| self.start() | |
| return self | |
| def __exit__(self, exc_type, exc_value, exc_traceback): | |
| self.stop() | |
| if __name__ == "__main__": | |
| # mp.set_start_method('spawn') | |
| with RealTimePlotter(["a", "b"], "out.jpg") as plotter: | |
| for i in range(10): | |
| y = np.random.random() | |
| plotter.update(0, i, y) | |
| plotter.update(1, i, 2 * y) | |
| time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment