CanvasAgg演示

此示例展示了如何直接使用AGG后端创建图像,对于希望完全控制其代码而不使用pylot界面来管理图形、图形关闭等的Web应用程序开发人员来说,这可能是有用的。

注意:没有必要避免使用图形前端 - 只需将后端设置为“Agg”就足够了。

在这个例子中,我们展示了如何将画布的内容保存到文件,以及如何将它们提取到一个字符串,该字符串可以传递给PIL或放在一个numpy数组中。 后一种功能允许例如使用没有文档到磁盘的cp脚本。

  1. from matplotlib.backends.backend_agg import FigureCanvasAgg
  2. from matplotlib.figure import Figure
  3. import numpy as np
  4. fig = Figure(figsize=(5, 4), dpi=100)
  5. # A canvas must be manually attached to the figure (pyplot would automatically
  6. # do it). This is done by instantiating the canvas with the figure as
  7. # argument.
  8. canvas = FigureCanvasAgg(fig)
  9. # Do some plotting.
  10. ax = fig.add_subplot(111)
  11. ax.plot([1, 2, 3])
  12. # Option 1: Save the figure to a file; can also be a file-like object (BytesIO,
  13. # etc.).
  14. fig.savefig("test.png")
  15. # Option 2: Save the figure to a string.
  16. canvas.draw()
  17. s, (width, height) = canvas.print_to_buffer()
  18. # Option 2a: Convert to a NumPy array.
  19. X = np.fromstring(s, np.uint8).reshape((height, width, 4))
  20. # Option 2b: Pass off to PIL.
  21. from PIL import Image
  22. im = Image.frombytes("RGBA", (width, height), s)
  23. # Uncomment this line to display the image using ImageMagick's `display` tool.
  24. # im.show()

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.backends.backend_agg.FigureCanvasAgg
  3. matplotlib.figure.Figure
  4. matplotlib.figure.Figure.add_subplot
  5. matplotlib.figure.Figure.savefig
  6. matplotlib.axes.Axes.plot

下载这个示例