简体   繁体   中英

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? I used matplotlib but I am keep running to errors. 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.

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> :

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM