How to Add Graphs to Flask apps (original) (raw)

Flask, being a lightweight web framework, does not have built-in support for graphing. However, it can easily integrate with powerful visualization libraries to generate dynamic and interactive charts because graphs and visualizations are an essential part of any web application that deals with data representation.

There are multiple ways to add graphs to Flask applications, but the two most common approaches that we are going to discuss in this article are:

  1. **Using Chart.js – A **JavaScript-based charting library that allows embedding graphs in HTML pages while passing data from Flask.
  2. **Using Bokeh – A **Python-based visualization library that enables interactive graphs without needing JavaScript coding.

Installation and Setup

To create a basic flask app, refer to- Create Flask App

After creating and activating a virtual environment install Flask and other libraries required in this project using this command-

pip install bokeh

Let's discuss both ways of adding graphs one by one.

Using Chart.js

**Chart.js is a popular **JavaScript library for creating interactive charts. It works well with Flask by passing data from the **backend to the **frontend using Jinja2 templating. This approach is simple, lightweight, and ideal for real-time data visualization in Flask applications.

Chart.js Integration in HTML

Create a chartjs-example.html file in the templates folder and in that file we include chart.js **CDN link in the HTML template and define a ****** element to render the graph.

**chartjs-example.html code:

HTML `

Chart.js Example
<!-- Store Flask data as a JavaScript variable -->
<script>
    const labels = JSON.parse('{{ labels | tojson | safe }}');
    const chartData = JSON.parse('{{ data | tojson | safe }}');

    const data = {
        labels: labels,
        datasets: [{
            label: 'Sales',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: chartData,
        }]
    };

    const config = {
        type: 'line',
        data: data,
        options: { maintainAspectRatio: false }
    };

    const myChart = new Chart(
        document.getElementById('myChart'),
        config
    );
</script>

`

**Code Explanation: