How to Add Graphs to Flask apps

How to Add Graphs to Flask apps

Adding graphs to a Flask application typically involves generating the graph on the server side (using a library like Matplotlib) and then sending it to the client (browser) to be displayed. This can be done in several ways, such as sending the graph as a static image or using an interactive graphing library like Plotly.

Method 1: Using Matplotlib to Generate Static Images

This method involves creating a graph using Matplotlib, saving it as an image, and then serving this image through Flask.

Step 1: Install Necessary Libraries

You need Flask and Matplotlib. Install them using pip if you haven't already:

pip install Flask matplotlib 

Step 2: Create a Flask App

Create a basic Flask application:

from flask import Flask, send_file import matplotlib.pyplot as plt import io app = Flask(__name__) @app.route('/') def show_graph(): # Create a plot plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) plt.title("Sample Plot") plt.xlabel("X-axis") plt.ylabel("Y-axis") # Save it to a temporary buffer. buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) # Send buffer in a response return send_file(buf, mimetype='image/png') if __name__ == '__main__': app.run(debug=True) 

In this example, when you navigate to the root URL, Flask triggers the show_graph function, which creates a simple plot, saves it to a byte buffer, and then sends that buffer as a response.

Step 3: Access the Graph

Run your Flask app, and navigate to http://localhost:5000 in your web browser. You should see the Matplotlib graph displayed.

Method 2: Using Plotly for Interactive Graphs

Plotly can create interactive graphs that can be embedded in Flask apps.

Step 1: Install Plotly

pip install plotly Flask 

Step 2: Create Flask App with Plotly Graph

from flask import Flask, render_template import plotly.graph_objs as go import plotly.io as pio import json app = Flask(__name__) @app.route('/') def show_plotly(): # Create a Plotly graph fig = go.Figure(data=[ go.Bar(x=[1, 2, 3], y=[4, 5, 6]) ]) fig.update_layout(title_text='Sample Plotly Graph') # Convert the figure to JSON graphJSON = json.dumps(fig, cls=pio.utils.PlotlyJSONEncoder) return render_template('graph.html', graphJSON=graphJSON) if __name__ == '__main__': app.run(debug=True) 

Step 3: Create a Template to Display the Graph

In your templates folder, create a file named graph.html:

<!DOCTYPE html> <html> <head> <title>Plotly Graph</title> </head> <body> <h1>My Plotly Graph</h1> <div id='divPlotly'></div> <script src='https://cdn.plot.ly/plotly-latest.min.js'></script> <script> var graphs = {{ graphJSON | safe }}; Plotly.newPlot('divPlotly', graphs); </script> </body> </html> 

Step 4: Access the Interactive Graph

Run your Flask app, and navigate to http://localhost:5000. You should see an interactive Plotly graph.

Note

  • For static images, remember that each request will generate and serve the image dynamically, which might not be efficient for frequently accessed plots.
  • For interactive graphs, Plotly is a powerful solution that allows for more complex and interactive visualizations.
  • Ensure proper handling of resources (like closing file streams) when working with image buffers or files.

More Tags

bitcoin compiler-construction oozie database-schema cashapelayer argmax electron-packager collision nsdateformatter flash-message

More Programming Guides

Other Guides

More Programming Examples