Chart.js 柱形图(Bar Chart)教程

Chart.js 提供了强大的柱形图(Bar Chart)功能,可以轻松创建可视化数据展示。本文将介绍如何使用 Chart.js 创建基本柱形图,并进行自定义配置。


1. 引入 Chart.js

1.1 通过 CDN(推荐)

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

1.2 通过 npm 安装

npm install chart.js

然后在 JavaScript 文件中导入:

import Chart from 'chart.js/auto';


2. 创建基本柱形图

2.1 添加 <canvas> 画布

<canvas id="barChart"></canvas>

2.2 在 JavaScript 中绘制柱形图

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

const barChart = new Chart(ctx, {
    type: 'bar', // 设置图表类型为柱形图
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: 'Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.5)',
                'rgba(54, 162, 235, 0.5)',
                'rgba(255, 206, 86, 0.5)',
                'rgba(75, 192, 192, 0.5)',
                'rgba(153, 102, 255, 0.5)',
                'rgba(255, 159, 64, 0.5)'
            ],
            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)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});


3. 横向柱形图(水平柱状图)

如果你希望创建 水平柱形图(horizontal bar chart),可以在 options 中添加 indexAxis: 'y'

const horizontalBarChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: 'Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'rgba(54, 162, 235, 0.5)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 1
        }]
    },
    options: {
        indexAxis: 'y', // 使柱形图水平显示
        scales: {
            x: {
                beginAtZero: true
            }
        }
    }
});


4. 多组数据(对比多个数据集)

如果你需要对比多个数据组,可以在 datasets 里添加多个数据集:

const multiBarChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
        datasets: [
            {
                label: 'Product A',
                data: [10, 20, 15, 25, 30],
                backgroundColor: 'rgba(255, 99, 132, 0.5)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            },
            {
                label: 'Product B',
                data: [15, 10, 25, 20, 35],
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }
        ]
    },
    options: {
        responsive: true,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});


5. 自定义柱形图

Chart.js 提供了多种自定义选项:

5.1 更改柱宽

options: {
    barThickness: 50, // 固定柱宽度(像素)
    maxBarThickness: 80 // 最大柱宽
}

5.2 圆角柱子

options: {
    elements: {
        bar: {
            borderRadius: 10 // 设置柱形图的圆角
        }
    }
}

5.3 显示数据标签

options: {
    plugins: {
        datalabels: {
            anchor: 'end',
            align: 'top',
            formatter: (value) => value + ' units'
        }
    }
}

需要额外安装 chartjs-plugin-datalabels

npm install chartjs-plugin-datalabels

然后在代码中引入:

import ChartDataLabels from 'chartjs-plugin-datalabels';
Chart.register(ChartDataLabels);


6. 更新和销毁图表

6.1 更新数据

barChart.data.datasets[0].data = [5, 10, 15, 20, 25, 30];
barChart.update();

6.2 销毁图表

barChart.destroy();


7. 交互功能

7.1 获取点击的柱子数据

document.getElementById('barChart').onclick = function(evt) {
    const points = barChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
    if (points.length > 0) {
        const datasetIndex = points[0].datasetIndex;
        const index = points[0].index;
        alert(`你点击了 ${barChart.data.labels[index]} 的 ${barChart.data.datasets[datasetIndex].label}`);
    }
};


总结

  • 创建柱形图:使用 type: 'bar' 创建基本柱形图。
  • 水平柱形图indexAxis: 'y' 使柱形图横向显示。
  • 多数据组柱形图:在 datasets 里添加多个数据。
  • 自定义样式:更改颜色、边框、圆角、数据标签等。
  • 交互功能:支持点击事件、更新数据、动态销毁等。

你想尝试哪种柱形图呢?😃