ChartJS 在条形图中显示数据集值. js

cu6pst1q  于 2023-06-22  发布在  Chart.js
关注(0)|答案(1)|浏览(168)

这是我的代码:

import Chart from 'chart.js/auto';

(function() {
    const data = [
        {
            name: 'Neighbour A',
            consumption: 720,
        },
        {
            name: 'Neighbour B',
            consumption: 745,
        },
        {
            name: 'Neighbour C',
            consumption: 917,
        },
        {
            name: 'My Household',
            consumption: 813,
        }
    ];

    new Chart(document.getElementById('consumptions'), {
        type: 'bar',
        data: {
            labels: data.map(m => m.name),
            datasets: [{
                label: 'Consumption',
                data: data.map(m => m.consumption),
                borderWidth: 1,
                barThickness: 40,
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                },
            }
        }
    })
})();

我想显示在工具栏内的工具提示中悬停显示的数据集值,水平。例如,我想要“720个单位”,水平放置,在第一个酒吧。
我还想减少每一条之间的间距。
请问我该怎么做?

uklbhaso

uklbhaso1#

经过几个小时的搜索,我偶然发现了datalabels插件,它帮助我实现了我想要的。

import Chart from 'chart.js/auto';
import ChartDataLabels from 'chartjs-plugin-datalabels';

const data = [
    {
        name: 'Neighbour A',
        consumption: 720,
    },
    {
        name: 'Neighbour B',
        consumption: 745,
    },
    {
        name: 'Neighbour C',
        consumption: 917,
    },
    {
        name: 'My Household',
        consumption: 813,
    }
];

const main = () => {
    Chart.register(ChartDataLabels);

    new Chart(document.getElementById('consumptions'), {
        type: 'bar',
        data: {
            labels: data.map(m => m.name),
            datasets: [{
                label: 'Consumption',
                data: data.map(m => m.consumption),
                borderWidth: 1,
                barThickness: 40,
            }]
        },
        options: {
            plugins: {
                datalabels: {
                    rotation: -90,
                    formatter: function (value) {
                        return `${value} units`
                    }
                }
            },
        }
    })
};

main();

这个插件在条形中显示数据集值,rotation: -90选项逆时针旋转90度,水平显示它们。

相关问题