在PNG中将networkx图形绘制到stdout / http响应 - python

Networkx在后台使用Matplotlib。

直接使用Matplotlib,提供图像的服务器脚本非常简单(为简单起见,使用Bottle):

import matplotlib.pyplot as plot
from matplotlib.backend.backends_agg import FigureCanvasAgg
from matplotlib.figure import Figure
from StringIO import StringIO
from bottle import route, response

@route("/plot.png")                                             
def serve_image():                                                   
    F = Figure()                              # new figure
    P = F.add_subplot(111)                    # new plot container inside the figure
    P.plot(list(range(10)), list(range(10)))  # simple plot
    PNG = StringIO()                          # container for PNG data
    canvas = FigureCanvasAgg(F)               # create image
    canvas.print_png(PNG)                     # draw image into the container
    response.content_type = "image/png"       # duh
    return PNG.getvalue()                     # return contents of the container

但是,Networkx似乎隐式使用Matplotlib,而不创建任何图形或子图实例。该手册通常可以归结为:

networkx.draw(my_graph)
plot.show()

如何将该图用作PNG图像?

python大神给出的解决方案

我对networkx并不是特别熟悉,但是在take an ax kwarg看来,它指定了要绘制的Axes对象。

在您的情况下,这将是您的P对象,由fig.add_subplot返回。

通常,执行此操作的代码如下所示:

def blah(data, ax=None):
    if ax is None:
        ax = plt.gca()
    return ax.plot(data)

因此,仅在未指定轴对象的情况下才调用pyplot状态机。只要传递手动创建的axes对象,就可以安全使用它。

查看networkx.draw,it appears to follow that pattern。