Note
Go to the endto download the full example code.
CanvasAgg demo#
This example shows how to use the agg backend directly to create images, whichmay be of use to web application developers who want full control over theircode without using the pyplot interface to manage figures, figure closing etc.
Note
It is not necessary to avoid using the pyplot interface in order tocreate figures without a graphical front-end - simply settingthe backend to "Agg" would be sufficient.
In this example, we show how to save the contents of the agg canvas to a file,and how to extract them to a numpy array, which can in turn be passed offtoPillow. The latter functionality allows e.g. to use Matplotlib inside acgi-scriptwithout needing to write a figure to disk, and to write images inany format supported by Pillow.
fromPILimportImageimportnumpyasnpfrommatplotlib.backends.backend_aggimportFigureCanvasAggfrommatplotlib.figureimportFigurefig=Figure(figsize=(5,4),dpi=100)# Do some plotting.ax=fig.add_subplot()ax.plot([1,2,3])# Option 1: Save the figure to a file; can also be a file-like object (BytesIO,# etc.).fig.savefig("test.png")# Option 2 (low-level approach to directly save to a numpy array): Manually# attach a canvas to the figure (pyplot or savefig would automatically do# it), by instantiating the canvas with the figure as argument; then draw the# figure, retrieve a memoryview on the renderer buffer, and convert it to a# numpy array.canvas=FigureCanvasAgg(fig)canvas.draw()rgba=np.asarray(canvas.buffer_rgba())# ... and pass it to PIL.im=Image.fromarray(rgba)# This image can then be saved to any format supported by Pillow, e.g.:im.save("test.bmp")# Uncomment this line to display the image using ImageMagick's `display` tool.# im.show()
References
The use of the following functions, methods, classes and modules is shownin this example: