def __onclick(self, event): """Manager to the click event on the figure.""" #Left click if event.button in (1, 2, 3) and event.inaxes: trans = event.inaxes.transData #Distance from nodes (in pixels) for node in self.drnodes.copy(): posit = self.pos[node] xn, yn = trans.transform(posit) dx, dy = (event.x - xn, event.y - yn) dist = sqrt(dx * dx + dy * dy) #Nodes have a 10-pixel radius if dist < 10: #The clicked button will define the action #Button 1: plot #If the branch is already plot, we just show it if event.button == 1: if node in self._subfigs: mgr = Gcf.get_fig_manager( self._subfigs[node].fig.number) mgr.window.activateWindow() mgr.window.raise_() else: #Else plot the observations signal = sig_buf.get_signal( sig_buf.get_available_leads()[0]) #We have to keep a reference to the object to avoid #garbage collection and loosing the event manager #see http://matplotlib.org/users/event_handling.html obsview = ObservationVisualizer(signal, node) mgr = Gcf.get_fig_manager(obsview.fig.number) mgr.window.move(0, 0) obsview.fig.canvas.set_window_title(str(node)) self._subfigs[node] = obsview obsview.draw() #Button 2: Add child nodes of the selected one to the plot. elif event.button == 2: pyperclip.copy(str(node)) stack = [node] while stack: n = stack.pop() self.drnodes.add(n) if n is node or not n.is_firm: stack.extend(self.graph[n].keys()) self.redraw() #Button 3: Copy the branch name to the clipboard elif event.button == 3: pyperclip.copy(str(node))
def open(self, fignum): self.fignum = int(fignum) manager = Gcf.get_fig_manager(self.fignum) manager.add_web_socket(self) _, _, w, h = manager.canvas.figure.bbox.bounds manager.resize(w, h) self.on_message('{"type":"refresh"}')
def visualize_dynamic(self): """ Dynamically visualizes the measurement data. To be used in the recording scripts. """ fig, axes, caxes = self._prepare_figure() self._dynamic = True self._figure = fig self._axes = axes self._caxes = caxes fig_manager = Gcf.get_fig_manager(fig.number) try: try: fig_manager.window.showMaximized() except: fig_manager.window.state('zoomed') except: # we are probably in the notebook regime fig.set_size_inches(10, 5) self._anim = animation.FuncAnimation(fig, self._plot, frames=self._yield_data, repeat=False, interval=100)
def __call__(self, fig=None, block=None): """ Show all figures. If *block* is not None, then it is a boolean that overrides all other factors determining whether show blocks by calling mainloop(). The other factors are: it does not block if run inside "ipython --pylab"; it does not block in interactive mode. """ if isinstance(fig, int): manager = Gcf.get_fig_manager(fig) else: manager = Gcf.get_active() if not manager: return # for manager in managers: manager.show() if block is not None: if block: self.mainloop() return else: return if not is_interactive() or get_backend() == 'WebAgg': self.mainloop()
def get(self, fignum, fmt): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) self.set_header( 'Content-Type', mimetypes.types_map.get(fmt, 'binary')) buff = BytesIO() manager.canvas.figure.savefig(buff, format=fmt) self.write(buff.getvalue())
def get(self, fignum, fmt): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) self.set_header('Content-Type', mimetypes.types_map.get(fmt, 'binary')) buff = BytesIO() manager.canvas.figure.savefig(buff, format=fmt) self.write(buff.getvalue())
def get(self): manager = Gcf.get_fig_manager(1) canvas = manager.canvas self.set_header('Content-Type', 'application/javascript') self.render("mpl_interface.js", toolitems=NavigationToolbar2WebAgg.toolitems, canvas=canvas)
def send_image(self): canvas = Gcf.get_fig_manager(self.fignum).canvas diff = canvas.get_diff_image() if self.supports_binary: self.write_message(diff, binary=True) else: data_uri = "data:image/png;base64,{0}".format( diff.encode('base64').replace('\n', '')) self.write_message(data_uri)
def get(self, fignum): with open(os.path.join(WebAggApplication._mpl_dirs["web_backend"], "mpl_interface.js")) as fd: tpl = fd.read() fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) t = tornado.template.Template(tpl) self.write(t.generate(toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas))
def on_message(self, message): message = json.loads(message) # The 'supports_binary' message is on a client-by-client # basis. The others affect the (shared) canvas as a # whole. if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: canvas = Gcf.get_fig_manager(self.fignum).canvas canvas.handle_event(message)
def get(self): manager = Gcf.get_fig_manager(1) canvas = manager.canvas self.set_header('Content-Type', 'application/javascript') self.render( "mpl_interface.js", toolitems=NavigationToolbar2WebAgg.toolitems, canvas=canvas)
def on_message(self, message): message = json.loads(message) # The 'supports_binary' message is on a client-by-client # basis. The others affect the (shared) canvas as a # whole. if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: manager = Gcf.get_fig_manager(self.fignum) manager.handle_json(message)
def get(self, fignum): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request, prefix=self.url_prefix) self.render("single_figure.html", prefix=self.url_prefix, ws_uri=ws_uri, fig_id=fignum, toolitems=core.NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas)
def get(self, fignum): with open( os.path.join(WebAggApplication._mpl_dirs['web_backend'], 'mpl_interface.js')) as fd: tpl = fd.read() fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) t = tornado.template.Template(tpl) self.write( t.generate(toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas))
def get(self, fignum): with open(os.path.join( os.path.dirname(__file__), 'web_backend', 'index.html')) as fd: tpl = fd.read() fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) t = tornado.template.Template(tpl) self.write(t.generate( toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas))
def get(self, fignum): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request, prefix=self.url_prefix) self.render( "single_figure.html", prefix=self.url_prefix, ws_uri=ws_uri, fig_id=fignum, toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas)
def on_message(self, message): message = json.loads(message) # The 'supports_binary' message is on a client-by-client # basis. The others affect the (shared) canvas as a # whole. if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: manager = Gcf.get_fig_manager(self.fignum) # It is possible for a figure to be closed, # but a stale figure UI is still sending messages # from the browser. if manager is not None: manager.handle_json(message)
def savefig(self, figure=None, **kwargs): """ Saves a :class:`~matplotlib.figure.Figure` to this file as a new page. Any other keyword arguments are passed to :meth:`~matplotlib.figure.Figure.savefig`. Parameters ---------- figure : :class:`~matplotlib.figure.Figure` or int, optional Specifies what figure is saved to file. If not specified, the active figure is saved. If a :class:`~matplotlib.figure.Figure` instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and # luatex<0.85; they were renamed to \pagewidth and \pageheight # on luatex>=0.85. self._file.write( br'\newpage' br'\ifdefined\pdfpagewidth\pdfpagewidth' br'\else\pagewidth\fi=%ain' br'\ifdefined\pdfpageheight\pdfpageheight' br'\else\pageheight\fi=%ain' b'%%\n' % (width, height) ) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas
def savefig(self, figure=None, **kwargs): if self.create_pngs: if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figh = manager.canvas.figure else: figh = figure figh.savefig(opj(self.png_folder, '%s_%d.%s' % (self.base_name, self.page_num, self.add_format)), format=self.add_format, dpi=200) self.page_num += 1 super().savefig(figure=figure, **kwargs)
def get(self, fignum): with open(os.path.join(WebAggApplication._mpl_dirs['web_backend'], 'single_figure.html')) as fd: tpl = fd.read() fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request, prefix=self.url_prefix) t = tornado.template.Template(tpl) self.write(t.generate( prefix=self.url_prefix, ws_uri=ws_uri, fig_id=fignum, toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas))
def get(self, fignum): with open( os.path.join(WebAggApplication._mpl_dirs['web_backend'], 'single_figure.html')) as fd: tpl = fd.read() fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request, prefix=self.url_prefix) t = tornado.template.Template(tpl) self.write( t.generate(prefix=self.url_prefix, ws_uri=ws_uri, fig_id=fignum, toolitems=NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas))
def join(self): stop_messages = { KeyboardInterrupt: "\nMeasurement interrupted!", AttributeError: "\nPlot has been closed, aborting!" } figure_number = self._measurement_result.get_figure_number() try: # wait for the measurement to end or for an interrupt while not self._measurement_result.is_finished(): # check if the window is still there manager = Gcf.get_fig_manager(figure_number) manager.canvas.start_event_loop(.1) except (KeyboardInterrupt, AttributeError) as e: print(stop_messages[type(e)]) self._interrupted = True finally: self._measurement_result.finalize() plt.close(figure_number)
def savefig(self, figure=None, **kwargs): """ Save a `.Figure` to this file as a new page. Any other keyword arguments are passed to `~.Figure.savefig`. Parameters ---------- figure : `.Figure` or int, default: the active figure The figure, or index of the figure, that is saved to the file. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and # luatex<0.85; they were renamed to \pagewidth and \pageheight # on luatex>=0.85. self._file.write( br'\newpage' br'\ifdefined\pdfpagewidth\pdfpagewidth' br'\else\pagewidth\fi=%ain' br'\ifdefined\pdfpageheight\pdfpageheight' br'\else\pageheight\fi=%ain' b'%%\n' % (width, height) ) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas
def on_message(self, message): message = json.loads(message) # The 'supports_binary' message is on a client-by-client # basis. The others affect the (shared) canvas as a # whole. if message['type'] == 'supports_binary': self.supports_binary = message['value'] elif message['type'] == 'ack': # Network latency tends to decrease if traffic is # flowing in both directions. Therefore, the browser # sends back an "ack" message after each image frame # is received. This could also be used as a simple # sanity check in the future, but for now the # performance increase is enough to justify it, even # if the server does nothing with it. pass else: canvas = Gcf.get_fig_manager(self.fignum).canvas canvas.handle_event(message)
def get(self, fmt): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) mimetypes = { 'ps': 'application/postscript', 'eps': 'application/postscript', 'pdf': 'application/pdf', 'svg': 'image/svg+xml', 'png': 'image/png', 'jpeg': 'image/jpeg', 'tif': 'image/tiff', 'emf': 'application/emf' } self.set_header('Content-Type', mimetypes.get(fmt, 'binary')) buff = io.BytesIO() manager.canvas.print_figure(buff, format=fmt) self.write(buff.getvalue())
def get(self, fignum, fmt): self.fignum = int(fignum) manager = Gcf.get_fig_manager(self.fignum) # TODO: Move this to a central location mimetypes = { "ps": "application/postscript", "eps": "application/postscript", "pdf": "application/pdf", "svg": "image/svg+xml", "png": "image/png", "jpeg": "image/jpeg", "tif": "image/tiff", "emf": "application/emf", } self.set_header("Content-Type", mimetypes.get(fmt, "binary")) buff = io.BytesIO() manager.canvas.print_figure(buff, format=fmt) self.write(buff.getvalue())
def get(self, fignum, fmt): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) # TODO: Move this to a central location mimetypes = { 'ps': 'application/postscript', 'eps': 'application/postscript', 'pdf': 'application/pdf', 'svg': 'image/svg+xml', 'png': 'image/png', 'jpeg': 'image/jpeg', 'tif': 'image/tiff', 'emf': 'application/emf' } self.set_header('Content-Type', mimetypes.get(fmt, 'binary')) buff = BytesIO() manager.canvas.figure.savefig(buff, format=fmt) self.write(buff.getvalue())
def get(self, fignum, format): self.fignum = int(fignum) manager = Gcf.get_fig_manager(self.fignum) # TODO: Move this to a central location mimetypes = { 'ps': 'application/postscript', 'eps': 'application/postscript', 'pdf': 'application/pdf', 'svg': 'image/svg+xml', 'png': 'image/png', 'jpeg': 'image/jpeg', 'tif': 'image/tiff', 'emf': 'application/emf' } self.set_header('Content-Type', mimetypes.get(format, 'binary')) buffer = io.BytesIO() manager.canvas.print_figure(buffer, format=format) self.write(buffer.getvalue())
def savefig(self, figure=None, **kwargs): """ Saves a :class:`~matplotlib.figure.Figure` to this file as a new page. Any other keyword arguments are passed to :meth:`~matplotlib.figure.Figure.savefig`. Parameters ---------- figure : :class:`~matplotlib.figure.Figure` or int, optional Specifies what figure is saved to file. If not specified, the active figure is saved. If a :class:`~matplotlib.figure.Figure` instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: self._file.write(self._build_newpage_command(width, height)) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas
def on_close(self): manager = Gcf.get_fig_manager(self.fignum) if manager is not None: manager.remove_web_socket(self)
def open(self, fignum): self.fignum = int(fignum) self.manager = Gcf.get_fig_manager(self.fignum) self.manager.add_web_socket(self) if hasattr(self, 'set_nodelay'): self.set_nodelay(True)
def on_close(self): Gcf.get_fig_manager(self.fignum).remove_web_socket(self)
def open(self, fignum): self.fignum = int(fignum) manager = Gcf.get_fig_manager(self.fignum) manager.add_web_socket(self) if hasattr(self, 'set_nodelay'): self.set_nodelay(True)