{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# CanvasAgg demo\n\nThis example shows how to use the agg backend directly to create images, which\nmay be of use to web application developers who want full control over their\ncode without using the pyplot interface to manage figures, figure closing etc.\n\n

Note

\n\nIt is not necessary to avoid using the pyplot interface in order to\ncreate figures without a graphical front-end - simply setting\nthe backend to \"Agg\" would be sufficient.\n\n
\n\nIn this example, we show how to save the contents of the agg canvas to a file,\nand how to extract them to a numpy array, which can in turn be passed off\nto [Pillow](https://pillow.readthedocs.io/). The latter functionality allows e.g. to use Matplotlib inside a\ncgi-script *without* needing to write a figure to disk, and to write images in\nany format supported by Pillow.\n\n.. redirect-from:: /gallery/misc/agg_buffer\n.. redirect-from:: /gallery/misc/agg_buffer_to_array\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from PIL import Image\n\nimport numpy as np\n\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\nfrom matplotlib.figure import Figure\n\nfig = Figure(figsize=(5, 4), dpi=100)\n\n# Do some plotting.\nax = fig.add_subplot()\nax.plot([1, 2, 3])\n\n# Option 1: Save the figure to a file; can also be a file-like object (BytesIO,\n# etc.).\nfig.savefig(\"test.png\")\n\n# Option 2 (low-level approach to directly save to a numpy array): Manually\n# attach a canvas to the figure (pyplot or savefig would automatically do\n# it), by instantiating the canvas with the figure as argument; then draw the\n# figure, retrieve a memoryview on the renderer buffer, and convert it to a\n# numpy array.\ncanvas = FigureCanvasAgg(fig)\ncanvas.draw()\nrgba = np.asarray(canvas.buffer_rgba())\n# ... and pass it to PIL.\nim = Image.fromarray(rgba)\n# This image can then be saved to any format supported by Pillow, e.g.:\nim.save(\"test.bmp\")\n\n# Uncomment this line to display the image using ImageMagick's `display` tool.\n# im.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.backends.backend_agg.FigureCanvasAgg`\n - `matplotlib.figure.Figure`\n - `matplotlib.figure.Figure.add_subplot`\n - `matplotlib.figure.Figure.savefig` / `matplotlib.pyplot.savefig`\n - `matplotlib.axes.Axes.plot` / `matplotlib.pyplot.plot`\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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }