Open In App

Responsive Chart with Bokeh, Flask and Python

Improve
Improve
Like Article
Like
Save
Share
Report

In this post, we will use the Flask framework to create our web application in Python. The Bokeh library will be used to create interactive graphs and we will visualize this graph through a simple frontend HTML page. For this, we will first write the endpoints in Flask which will help us to create Bokeh charts, and then we will create HTML templates that will utilize these Bokeh charts to display them to the user.

Flask is a web framework that offers libraries for creating simple web applications in Python. It is built using the Jinja2 template engine and the WSGI tools. Flask is considered a micro-framework. Web server gateway interface, sometimes known as WSGI, is a standard for creating web applications in Python. It is regarded as the specification for the common interface between the web application and server. Jinja2 is a web template engine that renders dynamic web pages by fusing a template with a specific data source. You can install Flask using the below command:

pip install flask

For building interactive visualizations for current web browsers, the Python library Bokeh is a good choice. It enables you to create stunning visualizations, from straightforward plots to interactive dashboards with streaming datasets. Without writing any JavaScript yourself, you may build visualizations that are powered by JavaScript using Bokeh. To install Bokeh use the below command:

pip install bokeh

Steps to Follow:

  1. Create a python file ‘main.py‘ that will contain the Flask App.
  2. Create a directory named ‘templates‘ and add an HTML file ‘charts.html‘.
  3. Run the Flask App and view the output in a browser.
  4. This is the file structure we will follow:
Responsive Chart with Bokeh, Flask and Python

 

Flask main.py

Here, we have created three Bokeh charts (scatter plot, bar chart, and line chart). We have used a single endpoint which is the root endpoint for our Flask application. For each chart, we get the HTML components to embed the charts in our template using the components() function. It returns the script and an HTML div tag assuming that the required JS files from Bokeh are already loaded in our template through the local URL or Bokeh’s CDN. The charts will be responsive due to the attribute ‘sizing_mode=”stretch_width”‘ used in each of the figures.

Python3




# Importing required functions
import random
  
from flask import Flask, render_template
from bokeh.embed import components
from bokeh.plotting import figure
  
# Flask constructor
app = Flask(__name__)
  
# Root endpoint
@app.route('/')
def homepage():
  
    # First Chart - Scatter Plot
    p1 = figure(height=350, sizing_mode="stretch_width")
    p1.circle(
        [i for i in range(10)],
        [random.randint(1, 50) for j in range(10)],
        size=20,
        color="navy",
        alpha=0.5
    )
  
    # Second Chart - Line Plot
    language = ['Python', 'JavaScript', 'C++', 'C#', 'Java', 'Golang']
    popularity = [85, 91, 63, 58, 80, 77]
  
    p2 = figure(
        x_range=language,
        height=350,
        title="Popularity",
    )
    p2.vbar(x=language, top=popularity, width=0.5)
    p2.xgrid.grid_line_color = None
    p2.y_range.start = 0
  
    # Third Chart - Line Plot
    p3 = figure(height=350, sizing_mode="stretch_width")
    p3.line(
        [i for i in range(10)],
        [random.randint(1, 50) for j in range(10)],
        line_width=2,
        color="olive",
        alpha=0.5
    )
  
    script1, div1 = components(p1)
    script2, div2 = components(p2)
    script3, div3 = components(p3)
  
    # Return all the charts to the HTML template
    return render_template(
        template_name_or_list='charts.html',
        script=[script1, script2, script3],
        div=[div1, div2, div3],
    )
  
  
# Main Driver Function
if __name__ == '__main__':
    # Run the application on the local development server
    app.run()


HTML Template

To create an HTML page, we will use the most popular Bootstrap framework. It has pre-defined CSS and JS classes which will help us to create a good-looking form with minimal code. For our purpose, we are using Bootstrap and CSS along with Bokeh JS. Bokeh JS contains all the required JavaScript functions to help the graphs with the required functionalities like loading data, zooming in or out, saving the graphs, etc. Please note that anything written within double curly braces ({{…}}) is interpreted as python code within the HTML template.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  
    <!-- <link href="http://cdn.bokeh.org/bokeh/release/bokeh-3.0.1.min.css" rel="stylesheet" type="text/css"> -->
        integrity="sha512-p7EUyPmeDeOwHiu7fIZNboAcQLxei3sWtXoHoShWWiPNUSRng/Xs5JPcaFPRa4dKy9IuHjyIQuLE4caGCwuewA=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  
    <title>Bokeh Charts</title>
</head>
  
<body>
  
    <div class="container">
        <h1 class="text-center py-4">Responsive Chart with Bokeh, Flask and Python</h1>
        <div class="row mb-5">
            <div class="col-md-6">
                <h4 class="text-center">Scatter Plot</h4>
                {{ div[0] | safe }}
                {{ script[0] | safe }}
            </div>
            <div class="col-md-6">
                <h4 class="text-center">Bar Chart</h4>
                {{ div[1] | safe }}
                {{ script[1] | safe }}
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <h4 class="text-center">Line Chart</h4>
                {{ div[2] | safe }}
                {{ script[2] | safe }}
            </div>
        </div>
    </div>
  
</body>
  
</html>


Running the Flask App

We can run the flask application (assuming the filename to be main.py) using the python main.py command in the terminal.

$ python main.py 
 * Serving Flask app 'main'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit

Output:

Then go to the URL http://127.0.0.1:5000 and you should be able to see the HTML template and the three Bokeh charts as shown below.

 



Last Updated : 01 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads