Visualizing Data with Python and Chart.js — A Step-by-Step Guide

Python with Chart.js can open up a world of possibilities for visualizing data. Python makes data handling straightforward, while Chart.js provides beautiful and interactive charts for the web. This article will walk you through how to use these tools together using real data from an SQLite database. We’ll cover extracting data with Python, transforming it, and displaying it with Chart.js.

Setting Up the Environment

Before diving into code, make sure you have the necessary tools. You’ll need Python and SQLite installed. For visualization, you’ll use Chart.js, which is a popular JavaScript library for creating responsive charts.

First, install the required Python packages:

pip install sqlite3 pandas flask

sqlite3 is a built-in module for working with SQLite databases. pandas helps manipulate data easily, and flask will serve the Chart.js page.

Creating the Database

Let’s start by setting up a simple SQLite database. Imagine you’re working with sales data from a small business.

import sqlite3

# Connect to the SQLite database
conn = sqlite3.connect('sales_data.db')
cursor = conn.cursor()

# Create a table for sales data
cursor.execute('''
CREATE TABLE IF NOT EXISTS sales (
    id INTEGER PRIMARY KEY,
    product TEXT,
    quantity INTEGER,
    price REAL,
    date TEXT
)
''')

# Insert sample data into the table
sample_data = [
    ('Laptop', 5, 900.00, '2024-09-01'),
    ('Mouse', 25, 20.00, '2024-09-02'),
    ('Keyboard', 15, 45.00, '2024-09-03'),
    ('Monitor', 10, 150.00, '2024-09-04'),
    ('Laptop', 3, 920.00, '2024-09-05'),
    ('Mouse', 30, 22.00, '2024-09-06')
]

cursor.executemany('INSERT INTO sales (product, quantity, price, date) VALUES (?, ?, ?, ?)', sample_data)
conn.commit()
conn.close()

This script creates a sales table and fills it with sample data. Each record includes product details, quantity sold, price, and date of the sale.

Fetching Data with Python

Now that you have a database, let’s fetch data and prepare it for visualization. For this example, you’ll extract the total sales quantity for each product.

import pandas as pd

# Reconnect to the database
conn = sqlite3.connect('sales_data.db')

# Read the data into a pandas DataFrame
df = pd.read_sql_query('SELECT product, SUM(quantity) as total_quantity FROM sales GROUP BY product', conn)

conn.close()

# Convert the DataFrame to a dictionary for Chart.js
data_dict = df.to_dict(orient='list')

This code reads the total sales quantity for each product into a DataFrame and converts it to a dictionary. The orient='list' parameter structures the dictionary in a way that Chart.js can use.

Setting Up Flask for Data Serving

To send this data to the front end, you’ll use Flask. Flask will serve the HTML and JavaScript needed to render the chart.

from flask import Flask, jsonify, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('chart.html')

@app.route('/data')
def data():
    return jsonify(data_dict)

if __name__ == '__main__':
    app.run(debug=True)

The index route serves an HTML file, which we’ll create shortly. The /data route sends the sales data to the front end in JSON format.

Creating the Chart with Chart.js

Now, create the chart.html file in a folder named templates:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <canvas id="salesChart" width="400" height="200"></canvas>
    <script>
        async function fetchData() {
            const response = await fetch('/data');
            const data = await response.json();
            return data;
        }

        async function createChart() {
            const data = await fetchData();
            const ctx = document.getElementById('salesChart').getContext('2d');
            const salesChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.product,
                    datasets: [{
                        label: 'Total Sales Quantity',
                        data: data.total_quantity,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        createChart();
    </script>
</body>
</html>

This HTML file creates a bar chart using Chart.js. It fetches the data from the Flask /data route and displays it. The fetchData function retrieves the data, while createChart initializes the chart with the data.

Running the Application

To see everything in action, run the Flask app:

python app.py

Navigate to http://127.0.0.1:5000/ in your browser. You should see a bar chart displaying total sales quantities for each product. You can now interact with the chart, hover over the bars, and see the data.


Thank you for following along with this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!

You can find the same tutorial on Medium.com.

Leave a Reply