{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Embedding WebAgg\n\n\nThis example demonstrates how to embed Matplotlib WebAgg interactive plotting\nin your own web application and framework. It is not necessary to do all this\nif you merely want to display a plot in a browser or use Matplotlib's built-in\nTornado-based server \"on the side\".\n\nThe framework being used must support web sockets.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import io\nimport json\nimport mimetypes\nfrom pathlib import Path\n\ntry:\n import tornado\nexcept ImportError as err:\n raise RuntimeError(\"This example requires tornado.\") from err\nimport tornado.web\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.websocket\n\n\nimport matplotlib as mpl\nfrom matplotlib.backends.backend_webagg_core import (\n FigureManagerWebAgg, new_figure_manager_given_figure)\nfrom matplotlib.figure import Figure\n\nimport numpy as np\n\n\ndef create_figure():\n \"\"\"\n Creates a simple example figure.\n \"\"\"\n fig = Figure()\n ax = fig.add_subplot(111)\n t = np.arange(0.0, 3.0, 0.01)\n s = np.sin(2 * np.pi * t)\n ax.plot(t, s)\n return fig\n\n\n# The following is the content of the web page. You would normally\n# generate this using some sort of template facility in your web\n# framework, but here we just use Python string formatting.\nhtml_content = \"\"\"\n\n \n \n \n \n \n \n \n\n \n\n matplotlib\n \n\n \n
\n \n\n\"\"\"\n\n\nclass MyApplication(tornado.web.Application):\n class MainPage(tornado.web.RequestHandler):\n \"\"\"\n Serves the main HTML page.\n \"\"\"\n\n def get(self):\n manager = self.application.manager\n ws_uri = \"ws://{req.host}/\".format(req=self.request)\n content = html_content % {\n \"ws_uri\": ws_uri, \"fig_id\": manager.num}\n self.write(content)\n\n class MplJs(tornado.web.RequestHandler):\n \"\"\"\n Serves the generated matplotlib javascript file. The content\n is dynamically generated based on which toolbar functions the\n user has defined. Call `FigureManagerWebAgg` to get its\n content.\n \"\"\"\n\n def get(self):\n self.set_header('Content-Type', 'application/javascript')\n js_content = FigureManagerWebAgg.get_javascript()\n\n self.write(js_content)\n\n class Download(tornado.web.RequestHandler):\n \"\"\"\n Handles downloading of the figure in various file formats.\n \"\"\"\n\n def get(self, fmt):\n manager = self.application.manager\n self.set_header(\n 'Content-Type', mimetypes.types_map.get(fmt, 'binary'))\n buff = io.BytesIO()\n manager.canvas.figure.savefig(buff, format=fmt)\n self.write(buff.getvalue())\n\n class WebSocket(tornado.websocket.WebSocketHandler):\n \"\"\"\n A websocket for interactive communication between the plot in\n the browser and the server.\n\n In addition to the methods required by tornado, it is required to\n have two callback methods:\n\n - ``send_json(json_content)`` is called by matplotlib when\n it needs to send json to the browser. `json_content` is\n a JSON tree (Python dictionary), and it is the responsibility\n of this implementation to encode it as a string to send over\n the socket.\n\n - ``send_binary(blob)`` is called to send binary image data\n to the browser.\n \"\"\"\n supports_binary = True\n\n def open(self):\n # Register the websocket with the FigureManager.\n manager = self.application.manager\n manager.add_web_socket(self)\n if hasattr(self, 'set_nodelay'):\n self.set_nodelay(True)\n\n def on_close(self):\n # When the socket is closed, deregister the websocket with\n # the FigureManager.\n manager = self.application.manager\n manager.remove_web_socket(self)\n\n def on_message(self, message):\n # The 'supports_binary' message is relevant to the\n # websocket itself. The other messages get passed along\n # to matplotlib as-is.\n\n # Every message has a \"type\" and a \"figure_id\".\n message = json.loads(message)\n if message['type'] == 'supports_binary':\n self.supports_binary = message['value']\n else:\n manager = self.application.manager\n manager.handle_json(message)\n\n def send_json(self, content):\n self.write_message(json.dumps(content))\n\n def send_binary(self, blob):\n if self.supports_binary:\n self.write_message(blob, binary=True)\n else:\n data_uri = \"data:image/png;base64,{0}\".format(\n blob.encode('base64').replace('\\n', ''))\n self.write_message(data_uri)\n\n def __init__(self, figure):\n self.figure = figure\n self.manager = new_figure_manager_given_figure(id(figure), figure)\n\n super().__init__([\n # Static files for the CSS and JS\n (r'/_static/(.*)',\n tornado.web.StaticFileHandler,\n {'path': FigureManagerWebAgg.get_static_file_path()}),\n\n # Static images for the toolbar\n (r'/_images/(.*)',\n tornado.web.StaticFileHandler,\n {'path': Path(mpl.get_data_path(), 'images')}),\n\n # The page that contains all of the pieces\n ('/', self.MainPage),\n\n ('/mpl.js', self.MplJs),\n\n # Sends images and events to the browser, and receives\n # events from the browser\n ('/ws', self.WebSocket),\n\n # Handles the downloading (i.e., saving) of static images\n (r'/download.([a-z0-9.]+)', self.Download),\n ])\n\n\nif __name__ == \"__main__\":\n figure = create_figure()\n application = MyApplication(figure)\n\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(8080)\n\n print(\"\")\n print(\"Press Ctrl+C to quit\")\n\n tornado.ioloop.IOLoop.instance().start()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.3" } }, "nbformat": 4, "nbformat_minor": 0 }