python - 如何在烧瓶中绘制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)
解决方案
您可以使用 flask 的 function send_file
,它接受文件名或类似文件的对象,为图像创建路由并使用另一个路由在模板中显示图像。
您可以像这样保存图表:
nx.draw(G)
with open(filepath, 'wb') as img:
plt.savefig(img)
plt.clf()
作为一个更完整的例子,这是我前段时间做的,一个烧瓶应用程序,它n-th
在路线上呈现完整的图表/<int:nodes>
:
服务器.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>
推荐阅读
- sql - SQL 乘以另一个表中的行时间值
- javascript - Can't print a method with es6 class
- ajax - Express.js and axios route timeout
- java - onClickListner in RecyclerViewer
- fortran - The accuracy of fortran double precision
- drop-down-menu - Materialise 的下拉菜单不起作用
- bash - 如何确定 bash 中是否安装了 npm 模块
- python - 将带有字符串的嵌套列表转换为 Pandas Dataframe
- node.js - Node.JS 字符串只匹配第一个字符
- validation - 表单数据验证