import matplotlib from matplotlib.lines import Line2D class DynamicSeries: """ AutomaticTimeSeries handles drawing a line in an efficient way onto a matplotlib canvas. """ def __init__(self, fig, ax): self.fig = fig self.ax = ax # Line associated with the figure used to draw the next line. self.dummyLine = ax.plot([0],[0], animated=True)[0] # Bitmap of previous background self._bg = None # Redraw time series on reveal. fig.canvas.mpl_connect("draw_event", self.on_draw) self.x_ax = [] self.y_ax = [] self.current_x_lims = 10 def insert(self, x, y): self.x_ax.append([x]) self.y_ax.append([y]) if len(self.x_ax) == 1: return None prev_x = self.x_ax[-1] prev_y = self.y_ax[-1] self.dummyLine.set_data([(prev_x, prev_y), (x, y)]) if self._bg is not None: self.fig.canvas.restore_region(self._bg) self.fig.draw_artist(self.dummyLine) self.fig.canvas.blit(self.fig.bbox) self.fig.canvas.flush_events() self._bg = self.fig.canvas.copy_from_bbox(self.fig.bbox) def on_invalidated(self): """ Redraw the entire canvas on invalidation. """ self.ax.clear() self.ax.set_xlim(0, self.current_x_lims) self.ax.plot(self.x_ax, self.y_ax, color="blue") def on_draw(self, event): self.on_invalidated() import matplotlib.pyplot as plt fig, ax = plt.subplots() fig.show() ats = AutomaticTimeSeries(fig, ax)