【问题标题】:how to draw networkX graph in flask?如何在烧瓶中绘制networkX图?
【发布时间】:2018-11-05 20:03:15
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

  • 给我们看一些代码!到目前为止,您尝试过什么?
  • @EdgarR.Mondragón 我刚刚添加到问题中!谢谢
  • @EdgarR.Mondragón 有什么办法可以在特定的 html 文件中返回图形吗?

标签: python matplotlib flask networkx


【解决方案1】:

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

你可以像这样保存你的图表:

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

作为一个更完整的例子,这是我前段时间做的一个烧瓶应用程序,它在路由 /<int:nodes> 处呈现 n-th 完整图:

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)

模板/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>

【讨论】:

  • 非常感谢 :) 我在网上找不到任何东西!我很感激!
  • 如何将图形/图像返回到特定的 html 页面?
猜你喜欢
  • 2013-10-13
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多