{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Embed in a web application server (Flask)\n\nWhen using Matplotlib in a web server it is strongly recommended to not use\npyplot (pyplot maintains references to the opened figures to make\n`~.matplotlib.pyplot.show` work, but this will cause memory leaks unless the\nfigures are properly closed).\n\nSince Matplotlib 3.1, one can directly create figures using the `.Figure`\nconstructor and save them to in-memory buffers. In older versions, it was\nnecessary to explicitly instantiate an Agg canvas (see e.g.\n:doc:`/gallery/user_interfaces/canvasagg`).\n\nThe following example uses Flask_, but other frameworks work similarly:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import base64\nfrom io import BytesIO\n\nfrom flask import Flask\n\nfrom matplotlib.figure import Figure\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello():\n # Generate the figure **without using pyplot**.\n fig = Figure()\n ax = fig.subplots()\n ax.plot([1, 2])\n # Save it to a temporary buffer.\n buf = BytesIO()\n fig.savefig(buf, format=\"png\")\n # Embed the result in the html output.\n data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")\n return f\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since the above code is a Flask application, it should be run using the\n[flask command-line tool](https://flask.palletsprojects.com/en/latest/cli/)\nAssuming that the working directory contains this script:\n\nUnix-like systems\n\n```console\nFLASK_APP=web_application_server_sgskip flask run\n```\nWindows\n\n```console\nset FLASK_APP=web_application_server_sgskip\nflask run\n```\n## Clickable images for HTML\n\nAndrew Dalke of [Dalke Scientific](http://www.dalkescientific.com)\nhas written a nice [article](http://www.dalkescientific.com/writings/diary/archive/2005/04/24/interactive_html.html)\non how to make html click maps with Matplotlib agg PNGs. We would\nalso like to add this functionality to SVG. If you are interested in\ncontributing to these efforts that would be great.\n\n" ] } ], "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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }