Flask and great looking charts using Chart.js

Flask piechart
Flask webapp with pie chart
In this article you will learn how to create great looking charts using Chart.js and Flask.

Chart.js is a javascript library to create simple and clean charts. All of them are HTML5 based, responsive, modular, interactive and there are in total 6 charts.

Related courses

Creating a bar chart app with Flask

We will start by creating a web application that displays a bar chart from a Python array. Create a directory /templates/ and add the file chart.html with this content:

< !DOCTYPE html><html lang="en"><head>   <meta charset="utf-8" />   <title>Chart.js </title>      <!-- import plugin script -->   <script src='static/Chart.min.js'></script>   </head><body>
<h1>Flask Chart.js</h1><!-- bar chart canvas element --><canvas id="chart" width="600" height="400"></canvas>
<script>
   // bar chart data
   var barData = {
   labels : [{% for item in labels %}
                  "{{item}}",
              {% endfor %}],
   datasets : [
      {
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
         data : [{% for item in values %}
                      {{item}},
                    {% endfor %}]
      }
      ]
   }
 
   // get bar chart canvas
   var mychart = document.getElementById("chart").getContext("2d");
 
   steps = 10
   max = 10
   // draw bar chart
   new Chart(mychart).Bar(barData, {
        scaleOverride: true,
        scaleSteps: steps,
        scaleStepWidth: Math.ceil(max / steps),
        scaleStartValue: 0,
        scaleShowVerticalLines: true,
        scaleShowGridLines : true,
        barShowStroke : true,
        scaleShowLabels: true
   });
 
</script>
</body></html>

Create the directory /static/ and add the file Chart.min.js to it. You can get it either from the Chart.js website or use the link. Finally go into the home directory and create app.py with this contents:

from flask import Flask
from flask import Markup
from flask import Flask
from flask import render_template
app = Flask(__name__)
 
@app.route("/")
def chart():
    labels = ["January","February","March","April","May","June","July","August"]
    values = [10,9,8,7,6,4,7,8]
    return render_template('chart.html', values=values, labels=labels)
 
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001)

Finally run:

python app.py
Open http://127.0.0.1:5001/ and you will see the array values[] plotted with the data in labels[].
We simply pass these two arrays to render_template(). This means that most of the magic occurs in the template. Chart.js is a client-side javascript library which is why our app.py is very minimal.
Result:
Flask barchart
Flask barchart

Continue reading “Flask and great looking charts using Chart.js”

Flask, JSON and the Google Charts API

This tutorial will teach you how to build a Flask app that combined with JSON and the Google Charts API. If you have no experience with Flask before I recommend reading my previous tutorials, they are great fun!

Related course
Complete Python Web Course: Build 8 Python Web Apps

Installing Flask

Install Flask using the command below:

$ pip install Flask

Create a file called hello.py

from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Hello World!"
 
if __name__ == "__main__":
    app.run()

Finally run the web app using this command:

$ python hello.py
* Running on http://localhost:5000/

Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.

Download Flask Examples

Get JSON data

To display awesome charts we first need some data. There are two common ways to get data in web apps: data from servers using an API (usually JSON) and data from databases. I use the Fixer.io JSON API to get some financial data, but any JSON API should do. If you are unfamiliar with JSON, see this article.

We wrote this script to get the exchange rates:

import json
import urllib2
 
def getExchangeRates():
    rates = []
    response = urllib2.urlopen('http://api.fixer.io/latest')
    data = response.read()
    rdata = json.loads(data, parse_float=float)
 
    rates.append( rdata['rates']['USD'] )
    rates.append( rdata['rates']['GBP'] )
    rates.append( rdata['rates']['JPY'] )
    rates.append( rdata['rates']['AUD'] )
    return rates
 
rates = getExchangeRates()
print rates

Google Charts API with Flask

With the Google Charts API you can display live data on your site. There are a lot of great charts there that are easy to add to your Flask app. We simply give the data that we got from the server through JSON and parsed, to the Google Charts API.

Create a flask app with the directory /templates/ for your templates. This is the main Flask code:

from flask import Flask, flash, redirect, render_template, request, session, abort
import os
import json
import urllib2
 
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__, template_folder=tmpl_dir)
 
def getExchangeRates():
    rates = []
    response = urllib2.urlopen('http://api.fixer.io/latest')
    data = response.read()
    rdata = json.loads(data, parse_float=float)
 
    rates.append( rdata['rates']['USD'] )
    rates.append( rdata['rates']['GBP'] )
    rates.append( rdata['rates']['HKD'] )
    rates.append( rdata['rates']['AUD'] )
    return rates
 
@app.route("/")
def index():
    rates = getExchangeRates()
    return render_template('test.html',**locals())      
 
@app.route("/hello")
def hello():
    return "Hello World!"
 
 
if __name__ == "__main__":
    app.run()

And we have this template:

{% block body %}
 
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <div id="chart_div"  style="width: 900px; height: 300px;"><div>
 
 
<script type='text/javascript'>//<![CDATA[ 
 
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBasic);
 
function drawBasic() {
 
      var data = google.visualization.arrayToDataTable([
        ['Currency', 'Rate', { role: 'style' }],
        ['USD', {{rates[0]}}, 'gold'],
        ['GBP', {{rates[1]}}, 'silver'],
        ['HKD', {{rates[2]}}, 'brown'],
        ['AUD', {{rates[3]}}, 'blue']
      ]);
 
      var options = {
        title: 'Exchange rate overview',
        chartArea: {width: '50%'},
        hAxis: {
          title: '',
          minValue: 0
        },
        vAxis: {
          title: ''
        }
      };
 
      var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
 
      chart.draw(data, options);
    }
//]]>  
 
</script>
 
 
{% endblock %}

Result:

Flask App
Flask App