| | """ |
| | ============== |
| | CanvasAgg demo |
| | ============== |
| | |
| | This example shows how to use the agg backend directly to create images, which |
| | may be of use to web application developers who want full control over their |
| | code without using the pyplot interface to manage figures, figure closing etc. |
| | |
| | .. note:: |
| | |
| | It is not necessary to avoid using the pyplot interface in order to |
| | create figures without a graphical front-end - simply setting |
| | the 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 off |
| | to Pillow_. The latter functionality allows e.g. to use Matplotlib inside a |
| | cgi-script *without* needing to write a figure to disk, and to write images in |
| | any format supported by Pillow. |
| | |
| | .. _Pillow: https://pillow.readthedocs.io/ |
| | .. redirect-from:: /gallery/misc/agg_buffer |
| | .. redirect-from:: /gallery/misc/agg_buffer_to_array |
| | """ |
| |
|
| | from PIL import Image |
| |
|
| | import numpy as np |
| |
|
| | from matplotlib.backends.backend_agg import FigureCanvasAgg |
| | from matplotlib.figure import Figure |
| |
|
| | fig = Figure(figsize=(5, 4), dpi=100) |
| | |
| | |
| | |
| | canvas = FigureCanvasAgg(fig) |
| |
|
| | |
| | ax = fig.add_subplot() |
| | ax.plot([1, 2, 3]) |
| |
|
| | |
| | |
| | fig.savefig("test.png") |
| |
|
| | |
| | |
| | canvas.draw() |
| | rgba = np.asarray(canvas.buffer_rgba()) |
| | |
| | im = Image.fromarray(rgba) |
| | |
| | im.save("test.bmp") |
| |
|
| | |
| | |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |
|