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 生成的画廊