Skip to content

Chart.js Basic Usage

After successfully including Chart.js, we can start using it to create various data visualization charts. This chapter will introduce the basic usage of Chart.js, including basic steps to create charts, data structures, and configuration options.

Basic Steps to Create a Chart

Using Chart.js to create a chart requires following basic steps:

1. Prepare HTML Structure

First, add a <canvas> element in HTML as chart container:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Chart.js Basic Usage</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <!-- Chart container -->
    <canvas id="myChart"></canvas>

    <script>
        // JavaScript code will be written here
    </script>
</body>
</html>

2. Get Canvas Context

Get the 2D drawing context of canvas element in JavaScript:

javascript
const ctx = document.getElementById('myChart').getContext('2d');

3. Create Chart Instance

Create chart instance using Chart constructor:

javascript
const myChart = new Chart(ctx, {
    type: 'bar',           // Chart type
    data: {               // Data configuration
        // ... data configuration
    },
    options: {            // Options configuration
        // ... options configuration
    }
});

Basic Chart Structure

The basic structure of Chart.js charts includes following parts:

1. Chart Type (type)

Specify the type of chart to create:

javascript
const myChart = new Chart(ctx, {
    type: 'bar',  // Bar chart
    // type: 'line',  // Line chart
    // type: 'pie',   // Pie chart
    // type: 'doughnut',  // Donut chart
    // ... other types
});

2. Data Configuration (data)

Data configuration includes labels and datasets:

javascript
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        // Labels (usually X-axis labels)
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],

        // Datasets
        datasets: [{
            label: 'Sales',           // Dataset label
            data: [12, 19, 3, 5, 2, 3], // Data values
            backgroundColor: 'rgba(54, 162, 235, 0.2)', // Background color
            borderColor: 'rgba(54, 162, 235, 1)',       // Border color
            borderWidth: 1                              // Border width
        }]
    }
});

3. Options Configuration (options)

Options configuration controls chart appearance and behavior:

javascript
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        // ... data configuration
    },
    options: {
        responsive: true,        // Responsive
        maintainAspectRatio: false, // Don't maintain aspect ratio
        scales: {               // Axis configuration
            y: {
                beginAtZero: true  // Y-axis starts from zero
            }
        }
    }
});

Complete Basic Example

Following is a complete basic usage example for Chart.js:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chart.js Basic Usage Example</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .chart-container {
            width: 80%;
            margin: 20px auto;
        }
    </style>
</head>
<body>
    <h1 style="text-align: center;">Chart.js Basic Usage Example</h1>

    <!-- Bar chart container -->
    <div class="chart-container">
        <canvas id="barChart"></canvas>
    </div>

    <!-- Line chart container -->
    <div class="chart-container">
        <canvas id="lineChart"></canvas>
    </div>

    <script>
        // Bar chart example
        const barCtx = document.getElementById('barChart').getContext('2d');
        const barChart = new Chart(barCtx, {
            type: 'bar',
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June'],
                datasets: [{
                    label: 'Sales (ten thousand)',
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 205, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 205, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Monthly Sales Bar Chart'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // Line chart example
        const lineCtx = document.getElementById('lineChart').getContext('2d');
        const lineChart = new Chart(lineCtx, {
            type: 'line',
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June'],
                datasets: [{
                    label: 'Visits',
                    data: [65, 59, 80, 81, 56, 55],
                    fill: false,
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }, {
                    label: 'Registered Users',
                    data: [28, 48, 40, 19, 86, 27],
                    fill: false,
                    borderColor: 'rgb(153, 102, 255)',
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Website Visits and Registered Users Line Chart'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    </script>
</body>
</html>

Data Updates

Chart.js supports dynamic chart data updates:

javascript
// Update data
barChart.data.datasets[0].data = [15, 25, 8, 12, 6, 9];
barChart.data.labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
barChart.update(); // Re-render chart

// Add new data point
barChart.data.labels.push('July');
barChart.data.datasets[0].data.push(18);
barChart.update();

// Remove data point
barChart.data.labels.pop();
barChart.data.datasets[0].data.pop();
barChart.update();

Chart Configuration Options

Chart.js provides rich configuration options to control chart appearance and behavior:

1. Responsive Configuration

javascript
options: {
    responsive: true,           // Enable responsive
    maintainAspectRatio: true, // Maintain aspect ratio
    aspectRatio: 2,           // Aspect ratio
}

2. Title and Legend Configuration

javascript
options: {
    plugins: {
        title: {
            display: true,
            text: 'Chart Title'
        },
        legend: {
            display: true,
            position: 'top' // 'top', 'bottom', 'left', 'right'
        }
    }
}

3. Animation Configuration

javascript
options: {
    animation: {
        duration: 1000,    // Animation duration (milliseconds)
        easing: 'easeInOutQuart' // Easing function
    }
}

4. Tooltip Configuration

javascript
options: {
    plugins: {
        tooltip: {
            enabled: true,
            mode: 'index',
            intersect: false
        }
    }
}

Common Methods

Chart.js instances provide some common methods:

1. update() - Update Chart

javascript
// Call after updating chart data
myChart.update();

2. destroy() - Destroy Chart

javascript
// Destroy chart instance
myChart.destroy();

3. resize() - Resize Chart

javascript
// Manually resize chart
myChart.resize();

4. reset() - Reset Chart

javascript
// Reset chart animation
myChart.reset();

Error Handling

When using Chart.js, you should add appropriate error handling:

javascript
try {
    const myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            // ... data configuration
        },
        options: {
            // ... options configuration
        }
    });
} catch (error) {
    console.error('Error creating chart:', error);
    // Display error message to user
    document.getElementById('chartContainer').innerHTML = '<p>Chart loading failed</p>';
}

Complete Practical Example

Following is a more complete practical example, showing how to create an interactive chart:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chart.js Complete Practical Example</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .chart-container {
            position: relative;
            height: 400px;
            margin: 20px 0;
        }
        .controls {
            text-align: center;
            margin: 20px 0;
        }
        button {
            margin: 5px;
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 style="text-align: center;">Chart.js Complete Practical Example</h1>

        <div class="controls">
            <button onclick="addData()">Add Data</button>
            <button onclick="removeData()">Remove Data</button>
            <button onclick="updateData()">Update Data</button>
            <button onclick="changeChartType()">Change Chart Type</button>
        </div>

        <div class="chart-container">
            <canvas id="myChart"></canvas>
        </div>
    </div>

    <script>
        // Initialize data
        const initialData = {
            labels: ['January', 'February', 'March', 'April', 'May', 'June'],
            datasets: [{
                label: 'Product A Sales',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            }, {
                label: 'Product B Sales',
                data: [8, 15, 7, 12, 9, 6],
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        };

        // Create chart
        const ctx = document.getElementById('myChart').getContext('2d');
        let myChart = new Chart(ctx, {
            type: 'bar',
            data: initialData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: 'Product Sales Data Chart'
                    },
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Sales (ten thousand)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Month'
                        }
                    }
                }
            }
        });

        // Add data
        function addData() {
            const months = ['July', 'August', 'September', 'October', 'November', 'December'];
            const randomMonth = months[Math.floor(Math.random() * months.length)];

            myChart.data.labels.push(randomMonth);
            myChart.data.datasets.forEach((dataset) => {
                dataset.data.push(Math.floor(Math.random() * 30));
            });
            myChart.update();
        }

        // Remove data
        function removeData() {
            if (myChart.data.labels.length > 1) {
                myChart.data.labels.pop();
                myChart.data.datasets.forEach((dataset) => {
                    dataset.data.pop();
                });
                myChart.update();
            }
        }

        // Update data
        function updateData() {
            myChart.data.datasets.forEach((dataset) => {
                dataset.data = dataset.data.map(() => Math.floor(Math.random() * 30));
            });
            myChart.update();
        }

        // Change chart type
        let chartType = 'bar';
        function changeChartType() {
            chartType = chartType === 'bar' ? 'line' : 'bar';
            myChart.destroy();

            myChart = new Chart(ctx, {
                type: chartType,
                data: myChart.data,
                options: myChart.options
            });
        }
    </script>
</body>
</html>

Through this chapter's learning, you should have mastered Chart.js basic usage. In the next chapter, we will deeply understand different chart types provided by Chart.js and their configuration options.

Content is for learning and research only.