[英]how to draw networkX graph in flask?
I am trying to to draw a graph with networkx and then show it in my flask webpage, but I dont know how to show it in my flask app?我正在尝试使用 networkx 绘制图形,然后将其显示在我的 Flask 网页中,但我不知道如何在我的 Flask 应用程序中显示它? I used matplotlib but I am keep running to errors.我使用了 matplotlib,但我一直在运行错误。 I dont know how to do this part!我不知道如何做这部分!
Any help would be appreciate it!任何帮助将不胜感激!
@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)
You can use flask's function send_file
, which accepts either a filename or a file-like object, to create a route for the image and use another route to show the image inside a template.您可以使用send_file
的函数send_file
,它接受文件名或类似文件的对象,为图像创建一个路由,并使用另一个路由在模板中显示图像。
You can save your graph plot like this:您可以像这样保存图形:
nx.draw(G)
with open(filepath, 'wb') as img:
plt.savefig(img)
plt.clf()
As a more complete example here's something I did some time ago, a flask app that renders the n-th
complete graph with at the route /<int:nodes>
:作为一个更完整的例子,这是我前段时间做的事情,一个flask应用程序,它在路由/<int:nodes>
处呈现第n-th
完整图:
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)
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.