卡纳瓦格演示

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

注解

为了在没有图形前端的情况下创建图形,不必避免使用Pyplot接口——只需将后端设置为“agg”就足够了。

在这个例子中,我们展示了如何将agg画布的内容保存到一个文件中,以及如何将它们提取到一个字符串中,而这个字符串又可以传递给pil或放入一个numpy数组中。后一个功能允许在CGI脚本中使用matplotlib 没有 需要将数字写入磁盘。

from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
import numpy as np

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(111)
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 view on the renderer buffer...
canvas.draw()
buf = canvas.buffer_rgba()
# ... convert to a NumPy array ...
X = np.asarray(buf)
# ... and pass it to PIL.
from PIL import Image
im = Image.fromarray(X)

# Uncomment this line to display the image using ImageMagick's `display` tool.
# im.show()

工具书类

以下函数、方法、类和模块的使用如本例所示:

出:

<function Axes.plot at 0x7faa00db6048>

关键词:matplotlib代码示例,codex,python plot,pyplot Gallery generated by Sphinx-Gallery