|
| 1 | +""" |
| 2 | +============== |
| 3 | +CanvasAgg demo |
| 4 | +============== |
| 5 | +
|
| 6 | +This example shows how to use the agg backend directly to create images, which |
| 7 | +may be of use to web application developers who want full control over their |
| 8 | +code without using the pyplot interface to manage figures, figure closing etc. |
| 9 | +
|
| 10 | +.. note:: |
| 11 | +
|
| 12 | + It is not necessary to avoid using the pyplot interface in order to |
| 13 | + create figures without a graphical front-end - simply setting |
| 14 | + the backend to "Agg" would be sufficient. |
| 15 | +
|
| 16 | +In this example, we show how to save the contents of the agg canvas to a file, |
| 17 | +and how to extract them to a string, which can in turn be passed off to PIL or |
| 18 | +put in a numpy array. The latter functionality allows e.g. to use Matplotlib |
| 19 | +inside a cgi-script *without* needing to write a figure to disk. |
| 20 | +""" |
| 21 | + |
| 22 | +from matplotlib.backends.backend_agg import FigureCanvasAgg |
| 23 | +from matplotlib.figure import Figure |
| 24 | +import numpy as np |
| 25 | + |
| 26 | +fig = Figure(figsize=(5, 4), dpi=100) |
| 27 | +# A canvas must be manually attached to the figure (pyplot would automatically |
| 28 | +# do it). This is done by instantiating the canvas with the figure as |
| 29 | +# argument. |
| 30 | +canvas = FigureCanvasAgg(fig) |
| 31 | + |
| 32 | +# Do some plotting. |
| 33 | +ax = fig.add_subplot(111) |
| 34 | +ax.plot([1, 2, 3]) |
| 35 | + |
| 36 | +# Option 1: Save the figure to a file; can also be a file-like object (BytesIO, |
| 37 | +# etc.). |
| 38 | +fig.savefig("test.png") |
| 39 | + |
| 40 | +# Option 2: Save the figure to a string. |
| 41 | +canvas.draw() |
| 42 | +s, (width, height) = canvas.print_to_buffer() |
| 43 | + |
| 44 | +# Option 2a: Convert to a NumPy array. |
| 45 | +X = np.fromstring(s, np.uint8).reshape((height, width, 4)) |
| 46 | + |
| 47 | +# Option 2b: Pass off to PIL. |
| 48 | +from PIL import Image |
| 49 | +im = Image.frombytes("RGBA", (width, height), s) |
| 50 | + |
| 51 | +# Uncomment this line to display the image using ImageMagick's `display` tool. |
| 52 | +# im.show() |
| 53 | + |
| 54 | +############################################################################# |
| 55 | +# |
| 56 | +# ------------ |
| 57 | +# |
| 58 | +# References |
| 59 | +# """""""""" |
| 60 | +# |
| 61 | +# The use of the following functions, methods, classes and modules is shown |
| 62 | +# in this example: |
| 63 | + |
| 64 | +import matplotlib |
| 65 | +matplotlib.backends.backend_agg.FigureCanvasAgg |
| 66 | +matplotlib.figure.Figure |
| 67 | +matplotlib.figure.Figure.add_subplot |
| 68 | +matplotlib.figure.Figure.savefig |
| 69 | +matplotlib.axes.Axes.plot |
0 commit comments