CanvasAgg 演示#

此示例演示如何直接使用 agg 后端来创建图像,这可能对希望完全控制代码而无需使用 pyplot 接口来管理图形、图形关闭等的 Web 应用程序开发人员有用。

注意

无需避免使用 pyplot 接口来创建没有图形前端的图形 - 只需将后端设置为 "Agg" 就足够了。

在此示例中,我们演示如何将 agg 画布的内容保存到文件,以及如何将其提取到 numpy 数组,该数组可以进一步传递给 Pillow。后一种功能允许例如在 cgi 脚本内使用 Matplotlib 无需 将图形写入磁盘,并以 Pillow 支持的任何格式写入图像。

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)
# A canvas must be manually attached to the figure (pyplot would automatically
# do it).  This is done by instantiating the canvas with the figure as
# argument.
canvas = FigureCanvasAgg(fig)

# 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: Retrieve a memoryview on the renderer buffer, and convert it to a
# numpy array.
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()

由 Sphinx-Gallery 生成的图库