Contents
Every Manager Loves Charts: Chart.js in 15 Minutes

Every Manager Loves Charts: Chart.js in 15 Minutes

"Give me a chart of those numbers!" 📊

I've heard those words a hundred times. A manager wants a dashboard and the deadline was yesterday. With Chart.js, that is no problem.

Prologue: Monday reality

javascript
// Monday morning 9:00
manager = "I need a dashboard with charts!"
ja = "OK, what charts?"
manager = "Sales, users, performance, everything!"
ja = "Deadline?"
manager = "By lunch!"
ja = "😰"

// Monday 9:05
ja = "import Chart from 'chart.js'"

// Monday 11:45
manager = "WOW! Amazing! 🤩"

// Chart.js for the win! 🎉

Why Chart.js?

javascript
alternativy = {
    "Excel charts": "❌ Not in the app",
    "D3.js": "❌ Too complex (three days of learning)",
    "Google Charts": "❌ External dependency",
    "Custom SVG": "❌ Reinventing the wheel",
    "Chart.js": "✅ Done in 15 minutes!"
}

verdikt = "Chart.js wins! 🏆"

Let's get started!


Chapter 1: Quick Start (5 Minutes)

Step 1: Installation

bash
# NPM
npm install chart.js

# CDN (for quick testing)
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Step 2: First Chart

html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>My First Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <canvas id="myChart" width="400" height="200"></canvas>
    
    <script>
        const ctx = document.getElementById('myChart');
        
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                datasets: [{
                    label: 'Salese 2024',
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    </script>
</body>
</html>

Total time: 2 minutes!

Open it in a browser → The chart is ready! 🎉


Chapter 2: Basic Chart Types

Bar Chart

A classic. Every manager knows and understands it.

javascript
const salesChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Q1', 'Q2', 'Q3', 'Q4'],
        datasets: [{
            label: 'Revenue (€)',
            data: [45000, 52000, 48000, 67000],
            backgroundColor: [
                'rgba(255, 99, 132, 0.6)',
                'rgba(54, 162, 235, 0.6)',
                'rgba(255, 206, 86, 0.6)',
                'rgba(75, 192, 192, 0.6)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Quarterly Revenue 2024'
            },
            legend: {
                display: true,
                position: 'bottom'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '€' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

When to use it:

✅ Compare values (quarters, products, teams)
✅ Time series (monthly sales)
✅ Rankings (top products)

Line Chart

When you want to show a trend. Is it going up or down? A manager can see immediately.

javascript
const performanceChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        datasets: [
            {
                label: 'Users 2024',
                data: [1200, 1350, 1400, 1380, 1500, 1650, 1800, 1950, 2100, 2250, 2400, 2600],
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                fill: true,
                tension: 0.4  // Smooth curve
            },
            {
                label: 'Users 2023',
                data: [800, 850, 900, 920, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300],
                borderColor: 'rgb(255, 99, 132)',
                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                fill: true,
                tension: 0.4,
                borderDash: [5, 5]  // Dashed line
            }
        ]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'User Growth Comparison',
                font: {
                    size: 18
                }
            },
            tooltip: {
                mode: 'index',
                intersect: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return value.toLocaleString() + ' users';
                    }
                }
            }
        }
    }
});

When to use it:

✅ Trends over time (growth, decline)
✅ Compare periods (year over year, month over month)
✅ Forecasts (with future projections)

Pie Chart

A manager favorite. It works every time, with percentages at a glance.

javascript
const marketShareChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['Product A', 'Product B', 'Product C', 'Product D', 'Other'],
        datasets: [{
            label: 'Podiel na trhu',
            data: [35, 25, 20, 12, 8],
            backgroundColor: [
                'rgba(255, 99, 132, 0.8)',
                'rgba(54, 162, 235, 0.8)',
                'rgba(255, 206, 86, 0.8)',
                'rgba(75, 192, 192, 0.8)',
                'rgba(153, 102, 255, 0.8)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)'
            ],
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Rozdelenie podielu na trhu'
            },
            legend: {
                position: 'right'
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        const label = context.label || '';
                        const value = context.parsed || 0;
                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                        const percentage = ((value / total) * 100).toFixed(1);
                        return `${label}: ${percentage}%`;
                    }
                }
            }
        }
    }
});

When to use it:

✅ Percentage breakdowns (market share, budget)
✅ Composition (team structure, tech stack)
✅ Proportions (traffic sources)

Doughnut Chart

Like a pie chart, but more modern looking. Managers love it.

javascript
const budgetChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['Development', 'Marketing', 'Operations', 'Sales', 'HR'],
        datasets: [{
            label: 'Budget Breakdown',
            data: [40, 25, 15, 12, 8],
            backgroundColor: [
                'rgba(255, 99, 132, 0.8)',
                'rgba(54, 162, 235, 0.8)',
                'rgba(255, 206, 86, 0.8)',
                'rgba(75, 192, 192, 0.8)',
                'rgba(153, 102, 255, 0.8)'
            ],
            hoverOffset: 4
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Annual Budget 2024'
            },
            legend: {
                position: 'bottom'
            }
        }
    }
});

When to use it:

✅ Similar to a pie chart (but prettier! 😎)
✅ Multiple datasets (inner and outer rings)

Chapter 3: A Real-World Dashboard

Here is what a manager really wants to see: a complete dashboard.

Sales dashboard

html
<!DOCTYPE html>
<html>
<head>
    <title>Sales Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        .dashboard {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }
        .card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .card.full-width {
            grid-column: 1 / -1;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stat-value {
            font-size: 32px;
            font-weight: bold;
            color: #4CAF50;
        }
        .stat-label {
            color: #666;
            font-size: 14px;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <h1>📊 Sales Dashboard 2024</h1>
    
    <!-- KPI karty -->
    <div class="stats">
        <div class="stat-card">
            <div class="stat-value">€212K</div>
            <div class="stat-label">Total revenue</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">2 547</div>
            <div class="stat-label">Total orders</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">€83</div>
            <div class="stat-label">Avg. order value</div>
        </div>
        <div class="stat-card">
            <div class="stat-value">+23%</div>
            <div class="stat-label">Year-over-year growth</div>
        </div>
    </div>
    
    <!-- Grafy -->
    <div class="dashboard">
        <div class="card full-width">
            <canvas id="revenueChart"></canvas>
        </div>
        
        <div class="card">
            <canvas id="productChart"></canvas>
        </div>
        
        <div class="card">
            <canvas id="regionChart"></canvas>
        </div>
    </div>
    
    <script src="dashboard.js"></script>
</body>
</html>
javascript
// dashboard.js

// Revenue chart (line)
const revenueCtx = document.getElementById('revenueChart');
new Chart(revenueCtx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        datasets: [
            {
                label: 'Revenue 2024',
                data: [15000, 18000, 16000, 22000, 19000, 25000, 28000, 26000, 30000, 32000, 35000, 38000],
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                fill: true,
                tension: 0.4
            },
            {
                label: 'Target',
                data: [20000, 20000, 20000, 20000, 20000, 25000, 25000, 25000, 30000, 30000, 35000, 35000],
                borderColor: 'rgba(255, 99, 132, 0.5)',
                borderDash: [10, 5],
                fill: false,
                pointRadius: 0
            }
        ]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Monthly Revenue vs Target',
                font: { size: 18 }
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return context.dataset.label + ': €' + context.parsed.y.toLocaleString();
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '€' + (value / 1000) + 'K';
                    }
                }
            }
        }
    }
});

// Product breakdown (doughnut)
const productCtx = document.getElementById('productChart');
new Chart(productCtx, {
    type: 'doughnut',
    data: {
        labels: ['Product A', 'Product B', 'Product C', 'Product D', 'Other'],
        datasets: [{
            data: [35, 28, 18, 12, 7],
            backgroundColor: [
                'rgba(255, 99, 132, 0.8)',
                'rgba(54, 162, 235, 0.8)',
                'rgba(255, 206, 86, 0.8)',
                'rgba(75, 192, 192, 0.8)',
                'rgba(153, 102, 255, 0.8)'
            ]
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Sales by Product'
            },
            legend: {
                position: 'bottom'
            }
        }
    }
});

// Regional sales (bar)
const regionCtx = document.getElementById('regionChart');
new Chart(regionCtx, {
    type: 'bar',
    data: {
        labels: ['Europe', 'North America', 'Asia', 'South America', 'Africa'],
        datasets: [{
            label: 'Sales (€)',
            data: [85000, 72000, 58000, 32000, 15000],
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Sales by Region'
            },
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '€' + (value / 1000) + 'K';
                    }
                }
            }
        }
    }
});

Chapter 4: Interactivity

Charts are not just for looking at. Let’s bring them to life.

Updating data

javascript
let myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
            label: 'Salese',
            data: [12, 19, 3, 5, 2, 3]
        }]
    }
});

// Updating data
function updateChart() {
    myChart.data.datasets[0].data = [15, 23, 8, 12, 7, 9];
    myChart.update();
}

// Add data
function addData() {
    myChart.data.labels.push('Jul');
    myChart.data.datasets[0].data.push(14);
    myChart.update();
}

// Remove data
function removeData() {
    myChart.data.labels.pop();
    myChart.data.datasets[0].data.pop();
    myChart.update();
}

Live data

This is what really impresses managers: real-time data.

html
<!DOCTYPE html>
<html>
<body>
    <canvas id="liveChart"></canvas>
    <button onclick="startLiveData()">Start</button>
    <button onclick="stopLiveData()">Stop</button>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        const ctx = document.getElementById('liveChart');
        
        const liveChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: 'Real-time data',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                scales: {
                    x: { display: true },
                    y: { beginAtZero: true }
                },
                animation: {
                    duration: 0  // Disabled for real time
                }
            }
        });
        
        let interval;
        
        function startLiveData() {
            interval = setInterval(() => {
                const now = new Date();
                const timeLabel = now.toLocaleTimeString();
                const value = Math.floor(Math.random() * 100);
                
                // Add new data
                liveChart.data.labels.push(timeLabel);
                liveChart.data.datasets[0].data.push(value);
                
                // Keep only the last 10 points
                if (liveChart.data.labels.length > 10) {
                    liveChart.data.labels.shift();
                    liveChart.data.datasets[0].data.shift();
                }
                
                liveChart.update();
            }, 1000);  // Update every second
        }
        
        function stopLiveData() {
            clearInterval(interval);
        }
    </script>
</body>
</html>

Clickable charts

javascript
const clickableChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Q1', 'Q2', 'Q3', 'Q4'],
        datasets: [{
            label: 'Revenue',
            data: [45000, 52000, 48000, 67000]
        }]
    },
    options: {
        onClick: (event, elements) => {
            if (elements.length > 0) {
                const element = elements[0];
                const datasetIndex = element.datasetIndex;
                const index = element.index;
                const label = clickableChart.data.labels[index];
                const value = clickableChart.data.datasets[datasetIndex].data[index];
                
                alert(`${label}: €${value.toLocaleString()}`);
                
                // Or navigate to the detail
                // window.location.href = `/detail/${label}`;
            }
        }
    }
});

Chapter 5: Framework Integration

Angular

typescript
// chart.component.ts

import { Component, OnInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

@Component({
  selector: 'app-chart',
  template: `
    <div class="chart-container">
      <canvas #chartCanvas></canvas>
    </div>
  `,
  styles: [`
    .chart-container {
      position: relative;
      height: 400px;
      width: 100%;
    }
  `]
})
export class ChartComponent implements OnInit, OnDestroy {
  @ViewChild('chartCanvas') chartCanvas!: ElementRef<HTMLCanvasElement>;
  private chart?: Chart;
  
  ngOnInit() {
    this.createChart();
  }
  
  private createChart() {
    const ctx = this.chartCanvas.nativeElement.getContext('2d');
    
    if (ctx) {
      this.chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
          datasets: [{
            label: 'Salese 2024',
            data: [12, 19, 3, 5, 2, 3],
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false
        }
      });
    }
  }
  
  updateData(newData: number[]) {
    if (this.chart) {
      this.chart.data.datasets[0].data = newData;
      this.chart.update();
    }
  }
  
  ngOnDestroy() {
    if (this.chart) {
      this.chart.destroy();
    }
  }
}

React

jsx
// ChartComponent.jsx

import React, { useEffect, useRef } from 'react';
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

function ChartComponent({ data, labels }) {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  
  useEffect(() => {
    if (chartRef.current) {
      const ctx = chartRef.current.getContext('2d');
      
      // Destroy the existing chart
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
      
      // Create a new chart
      chartInstance.current = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: 'Salese',
            data: data,
            backgroundColor: 'rgba(54, 162, 235, 0.6)'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false
        }
      });
    }
    
    // Cleanup
    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [data, labels]);
  
  return (
    <div style={{ position: 'relative', height: '400px' }}>
      <canvas ref={chartRef}></canvas>
    </div>
  );
}

export default ChartComponent;

Vue

vue
<!-- ChartComponent.vue -->

<template>
  <div class="chart-container">
    <canvas ref="chartCanvas"></canvas>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

export default {
  name: 'ChartComponent',
  props: {
    data: { type: Array, required: true },
    labels: { type: Array, required: true }
  },
  data() {
    return { chart: null };
  },
  mounted() {
    this.createChart();
  },
  watch: {
    data() {
      this.updateChart();
    }
  },
  methods: {
    createChart() {
      const ctx = this.$refs.chartCanvas.getContext('2d');
      
      this.chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.labels,
          datasets: [{
            label: 'Data',
            data: this.data,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.4
          }]
        },
        options: { responsive: true }
      });
    },
    updateChart() {
      if (this.chart) {
        this.chart.data.datasets[0].data = this.data;
        this.chart.update();
      }
    }
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.destroy();
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;
  height: 400px;
}
</style>

Chapter 6: Advanced Customization

Gradients

This looks professional. The manager will be impressed.

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

// Vytvorenie gradientu
const gradient = ctx.getContext('2d').createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(75, 192, 192, 0.8)');
gradient.addColorStop(0.5, 'rgba(75, 192, 192, 0.4)');
gradient.addColorStop(1, 'rgba(75, 192, 192, 0.1)');

new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
            label: 'Revenue',
            data: [15, 23, 18, 28, 32, 38],
            backgroundColor: gradient,  // Use the gradient
            borderColor: 'rgb(75, 192, 192)',
            fill: true,
            tension: 0.4
        }]
    }
});

Custom tooltips

javascript
new Chart(ctx, {
    type: 'line',
    data: { /* ... */ },
    options: {
        plugins: {
            tooltip: {
                enabled: true,
                backgroundColor: 'rgba(0, 0, 0, 0.9)',
                titleColor: '#fff',
                bodyColor: '#fff',
                borderColor: '#4CAF50',
                borderWidth: 2,
                displayColors: true,
                padding: 15,
                callbacks: {
                    title: function(context) {
                        return 'Mesiac: ' + context[0].label;
                    },
                    label: function(context) {
                        return 'Revenue: €' + context.parsed.y.toLocaleString();
                    },
                    afterLabel: function(context) {
                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                        const percentage = ((context.parsed.y / total) * 100).toFixed(1);
                        return `(${percentage}% z celku)`;
                    }
                }
            }
        }
    }
});

Annotations

Target lines and highlighted periods distinguish an amateur chart from a professional one.

bash
# Install the plugin
npm install chartjs-plugin-annotation
javascript
import annotationPlugin from 'chartjs-plugin-annotation';
Chart.register(annotationPlugin);

new Chart(ctx, {
    type: 'line',
    data: { /* ... */ },
    options: {
        plugins: {
            annotation: {
                annotations: {
                    // Horizontal line (target)
                    targetLine: {
                        type: 'line',
                        yMin: 25000,
                        yMax: 25000,
                        borderColor: 'red',
                        borderWidth: 2,
                        borderDash: [10, 5],
                        label: {
                            content: 'Target: €25K',
                            enabled: true,
                            position: 'end'
                        }
                    },
                    // Highlight a period
                    summerHighlight: {
                        type: 'box',
                        xMin: 'Jun',
                        xMax: 'Aug',
                        backgroundColor: 'rgba(255, 206, 86, 0.2)',
                        borderColor: 'rgba(255, 206, 86, 0.5)',
                        borderWidth: 1,
                        label: {
                            content: 'Summer peak',
                            enabled: true,
                            position: 'center'
                        }
                    }
                }
            }
        }
    }
});

Chapter 7: Performance Tips

Large datasets

With thousands of points, a chart can slow down. Here is a solution:

javascript
const largeDataChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: Array.from({ length: 1000 }, (_, i) => i),
        datasets: [{
            label: 'Large dataset',
            data: Array.from({ length: 1000 }, () => Math.random() * 100),
            borderWidth: 1,
            pointRadius: 0  // ✅ Do not draw points (faster!)
        }]
    },
    options: {
        animation: false,  // ✅ Disable animations (faster!)
        parsing: false,    // ✅ Assume data is already parsed
        normalized: true,  // ✅ Data is already normalized
        responsive: true,
        scales: {
            x: {
                type: 'linear',
                ticks: {
                    maxTicksLimit: 20  // ✅ Limit the number of ticks
                }
            }
        }
    }
});

Lazy loading

Load a chart only when it is visible to save resources.

javascript
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            // The chart is visible; create it
            createChart();
            observer.unobserve(entry.target);
        }
    });
});

observer.observe(document.getElementById('myChart'));

function createChart() {
    // Vytvorenie grafu tu
}

Chapter 8: Common Use Cases

KPI Dashboard so sparklines

Small charts, big impression.

javascript
function createSparkline(canvasId, data, color) {
    new Chart(document.getElementById(canvasId), {
        type: 'line',
        data: {
            labels: Array.from({ length: data.length }, (_, i) => i),
            datasets: [{
                data: data,
                borderColor: color,
                borderWidth: 2,
                fill: false,
                pointRadius: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: { enabled: false }
            },
            scales: {
                x: { display: false },
                y: { display: false }
            }
        }
    });
}

// Usage:
createSparkline('revenueSparkline', [12, 15, 13, 17, 20, 18, 22], '#4CAF50');
createSparkline('usersSparkline', [100, 120, 115, 130, 145, 140, 160], '#2196F3');

Comparison chart

javascript
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Q1', 'Q2', 'Q3', 'Q4'],
        datasets: [
            {
                label: '2023',
                data: [45, 52, 48, 67],
                backgroundColor: 'rgba(255, 99, 132, 0.6)'
            },
            {
                label: '2024',
                data: [55, 62, 58, 77],
                backgroundColor: 'rgba(54, 162, 235, 0.6)'
            }
        ]
    },
    options: {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Year-over-year comparison'
            }
        },
        scales: {
            y: { beginAtZero: true }
        }
    }
});

Stacked chart

javascript
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [
            {
                label: 'Online predaje',
                data: [30, 35, 32, 38, 40, 45],
                backgroundColor: 'rgba(54, 162, 235, 0.8)'
            },
            {
                label: 'Salese v obchode',
                data: [20, 22, 18, 25, 28, 30],
                backgroundColor: 'rgba(255, 206, 86, 0.8)'
            },
            {
                label: 'Partner sales',
                data: [10, 12, 15, 14, 18, 20],
                backgroundColor: 'rgba(75, 192, 192, 0.8)'
            }
        ]
    },
    options: {
        responsive: true,
        scales: {
            x: { stacked: true },
            y: { stacked: true, beginAtZero: true }
        },
        plugins: {
            title: {
                display: true,
                text: 'Sales channel breakdown'
            }
        }
    }
});

Chapter 9: Best Practices

DO ✅

javascript
// 1. Destroy charts when they are no longer needed
const myChart = new Chart(ctx, {...});

// When the component is destroyed:
myChart.destroy();  // ✅ Free memory

// 2. Use responsive options
options: {
    responsive: true,
    maintainAspectRatio: false  // Allows height control
}

// 3. Format large numbers
ticks: {
    callback: function(value) {
        return '€' + (value / 1000) + 'K';  // 25000 → €25K
    }
}

// 4. Set beginAtZero for bar and line charts
scales: {
    y: {
        beginAtZero: true  // ✅ Start at 0
    }
}

// 5. Use appropriate colors (accessibility)
// Good contrast, with a colorblind-friendly palette

DO NOT ❌

javascript
// 1. Do not create multiple charts on the same canvas
const chart1 = new Chart(ctx, {...});
const chart2 = new Chart(ctx, {...});  // ❌ It will break!

// 2. Do not forget to update after changing data
myChart.data.datasets[0].data = [1, 2, 3];
// Missing: myChart.update();  // ❌

// 3. Do not use too many points without decimation
data: Array.from({ length: 100000 }, () => ...)  // ❌ Slow!

// 4. Do not use animations for real-time data
animation: {
    duration: 1000  // ❌ Lags during live updates
}

// Namiesto toho:
animation: false  // ✅

Conclusion: The Manager’s Checklist

javascript
poziadavky_managera = {
    "Clear charts": "✅ Chart.js",
    "Fast to create": "✅ 15 minutes",
    "Interactive": "✅ Click, hover, zoom",
    "Responsive": "✅ Works on mobile",
    "Customizable": "✅ Colors, styles, tooltips",
    "Real-time data": "✅ Live updates",
    "Export": "✅ PNG, PDF (plugins)"
};

verdikt = "The manager is happy! 🎉";

Key takeaways:

Chart types:
- Bar: Comparisons
- Line: Trendy
- Pie/Doughnut: Proportions
- Mixed: Complex data

Integration:
✅ Vanilla JS
✅ Angular
✅ React
✅ Vue

Performance:
✅ Disable animations for large datasets
✅ Use decimation
✅ Lazy loading
✅ Destroy when no longer needed

Customization:
✅ Gradients
✅ Custom tooltips
✅ Annotations
✅ Plugins

Resources:

Documentation: https://www.chartjs.org/docs/
Samples: https://www.chartjs.org/samples/
Plugins: https://github.com/chartjs
CDN: https://cdn.jsdelivr.net/npm/chart.js

Written by a developer who knows managers love charts. Chart.js is the answer. 15 minutes → happy manager. 📊

P.S.: Every meeting begins with "Show me a chart". Be prepared! 😊

P.P.S.: Pie charts are a manager favorite. They always work! 🥧

P.P.P.S.: A line chart with targets = instant approval. Trust me. 📈

All articles