如何在烧瓶中绘制networkX图?

时间:2018-11-05 20:03:16

标签: python matplotlib flask networkx

我正在尝试使用networkx绘制图形,然后将其显示在我的烧瓶网页中,但是我不知道如何在我的烧瓶应用程序中显示它?我使用了matplotlib,但是我一直在出错。我不知道该怎么做!

任何帮助将不胜感激!

@app.route('/graph')
def graph_draw():
    F = Figure()

    G = nx.Graph()   
    G.add_node(1)
    G.add_nodes_from([2, 3])
    H = nx.path_graph(10)
    G.add_nodes_from(H)
    G.add_node(H)
    G.add_edge(1, 2)
    nx.draw(G)
    p = plt.show()

return render_template('indexExtra.html',p=p)

1 个答案:

答案 0 :(得分:0)

您可以使用flask函数send_file(接受文件名或类似文件的对象)为图像创建路由,并使用另一条路由在模板内显示图像。

您可以这样保存图形图:

nx.draw(G)
with open(filepath, 'wb') as img:
    plt.savefig(img)
    plt.clf()

作为更完整的示例,这是我前段时间所做的事情,一个烧瓶应用程序使用n-th路线绘制了/<int:nodes>完整图形:

server.py

from flask import Flask, render_template, send_file
import matplotlib.pyplot as plt
from io import BytesIO
import networkx as nx


app = Flask(__name__)

@app.route('/<int:nodes>')
def ind(nodes):
    return render_template("image.html", nodes=nodes)

@app.route('/graph/<int:nodes>')
def graph(nodes):
    G = nx.complete_graph(nodes)
    nx.draw(G)

    img = BytesIO() # file-like object for the image
    plt.savefig(img) # save the image to the stream
    img.seek(0) # writing moved the cursor to the end of the file, reset
    plt.clf() # clear pyplot

    return send_file(img, mimetype='image/png')

if __name__ == '__main__':
    app.run(debug=True)

templates / image.html

<html>
  <head>
    <title>Graph</title>
  </head>
  <body>
    <h1>Graph</h1>
    <img
       src="{{ url_for('graph', nodes=nodes) }}"
       alt="Complete Graph with {{ nodes }} nodes"
       height="200"
    />
  </body>
</html>