备注
Go to the end 下载完整的示例代码..
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()
参考
以下函数,方法,类和模块的用法在本例中显示:
matplotlib.backends.backend_agg.FigureCanvasAggmatplotlib.figure.Figurematplotlib.figure.Figure.add_subplotmatplotlib.figure.Figure.savefig/matplotlib.pyplot.savefigmatplotlib.axes.Axes.plot/matplotlib.pyplot.plot