Home / Blogs

How to Create a Stacked Bar Chart Using Chart.js

Django
·

January 17, 2024

how-to-create-a-stacked-bar-chart-using-chart-js

In Horilla, the dashboard of each module is equipped with a variety of charts designed to enhance understanding by presenting details in a visually intuitive manner. These charts, featured across all dashboards, are generated using Chart.js — a powerful and versatile JavaScript charting library that is both free and open source.

In this blog, we’ll learn how to make a stacked bar chart using Chart.js.

The Employee Payslip chart from the Horilla Payroll Software Dashboard is an example of a stacked bar chart.

First, create a virtual environment for the Django web application. Install Django, install all the requirements, and start the project and configure the chart js cdn in the index page —check out our ‘How To Build a Real-Time Dashboard with Django and Chart.js‘ blog for a guide on that. After creating the app and configuring the views, URLs,  and template, let’s begin by writing the views.py function for values to display in the chart.

class ChartData(models.Model):
    label = models.CharField(max_length=255)
    data1 = models.IntegerField()
    data2 = models.IntegerField()
    data3 = models.IntegerField()

We want to send the values to the template to make the chart using this model. For that in views.py,

from django.shortcuts import render
from .models import ChartData

def stacked_bar_chart(request):
    data = ChartData.objects.all()
    labels = [item.label for item in data]
    data1 = [item.data1 for item in data]
    data2 = [item.data2 for item in data]
    data3 = [item.data3 for item in data]
    
    context = {
        'labels': labels,
        'data1': data1,
        'data2': data2,
        'data3': data3,
    }


    return render(request, 'stacked_bar_chart.html', context=context)

Here labels, data1, data2, and data3 all are lists and rendered into a stacked_bar_chart.html page.

In the HTML page, there needs to be a canvas tag with a unique ID.

<canvas id="myChart" width="400" height="200"></canvas>

We use jQuery to create the chart in the canvas, inside the script tag, and initialize the chart by,

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [],
        datasets: [
            {
                        label: 'Data1',
                        data: [],
                        backgroundColor: 'rgba(255, 99, 132, 0.7)',
                    },
                    {
                        label: 'Data2',
                        data: [],
                        backgroundColor: 'rgba(54, 162, 235, 0.7)',
                    },
                    {
                        label: 'Data3',
                        data: [],
                        backgroundColor: 'rgba(255, 206, 86, 0.7)',
                    },

        ]
    },
    options: {
        scales: {
            x: {
                stacked: true
            },
            y: {
                stacked: true
            }
        }
    }

This section initializes the Chart.js instance with a bar chart. The myChart object is created using the canvas context with the ID myChart.

The chart is configured with three datasets (Data1, Data2, and Data3), each with an initially empty array for data. The chart is set to be stacked on both the X and Y axes.

function fetchData() {
    $.ajax({
        url: '{% url "stacked_bar_chart" %}',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            updateChart(data);
        },
        error: function (error) {
            console.log('Error fetching data:', error);
        }
    });
}

This function makes an AJAX request to the server to fetch data. The URL is determined by the Django template tag {% url “stacked_bar_chart” %}, which should be replaced with the actual URL endpoint in your Django application.

The expected response is in JSON format, and if the request is successful, the updateChart function is called with the retrieved data. If there’s an error, a message is logged to the console.

Now update the chart by,

function updateChart(data) {
    myChart.data.labels = data.labels;
    myChart.data.datasets[0].data = data.data1;
    myChart.data.datasets[1].data = data.data2;
    myChart.data.datasets[2].data = data.data3;
    myChart.update();
}

This function updates the chart with new data. It modifies the labels and dataset values for each of the three datasets (Data1, Data2, and Data3), and then it calls myChart.update() to redraw the chart with the updated data.

Result:

In this tutorial, we successfully integrated Chart.js with Django to create a dynamic stacked bar chart by incorporating AJAX to fetch data from the backend. This combination of Django’s backend capabilities and Chart.js’s frontend charting provides a robust foundation for building interactive and visually appealing data visualizations in web applications.

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.