首页 > 解决方案 > ChartJS 如何将颜色设置为一个栏

问题描述

我有这个条形图,我很难通过脚本将颜色设置为索引的一个条形。贝娄是我的图表条码:

    var ctx = document.getElementById("myBarChart");
var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [],
        datasets: [{
            label: "Valor",
            backgroundColor: "rgba(2,117,216,1)",
            borderColor: "rgba(2,117,216,1)",
            data: [],
        }],
    },
    options: {
        plugins: {
            datalabels: {
                anchor: 'end',
                align: 'top',
                formatter: function (value, context) {
                    if (value != 0) {
                        return new Date(value * 1000).toISOString().substr(11, 8);
                    } else {
                        value = " "
                        return value;
                    }
                },
                font: {
                    weight: 'bold'
                }
            }
        },
        responsive: true,
        tooltips: {
            /*  intersect: false, */
            callbacks: {
                title: function (tooltipItem, data) {
                    return data['labels'][tooltipItem[0]['index']];
                },
                label: function (tooltipItem, data) {
                    return new Date(parseInt(data['datasets'][0]['data'][tooltipItem[
                        'index']]) * 1000).toISOString().substr(11,
                        8);
                },
            },
        },
        scales: {
            xAxes: [{
                time: {
                    unit: 'month'
                },
                gridLines: {
                    display: false
                },
            }],
            yAxes: [{
                ticks: {
                    min: 0,
                    suggestedMax: 36000,
                    stepSize: 3600,
                    beginAtZero: true,
                },
            }],
        },
    }
});

我试过这个:myBarChart.data.datasets[0].backgroundColor[0]

但它不起作用。如果有人知道如何在最新版本的 chartjs 中执行此操作,请帮助我。

标签: javascriptchartschart.js

解决方案


您可以为该backgroundColor属性提供一个数组。在此数组中,您可以使用默认颜色填充它,但您希望条形图为不同颜色的索引除外


推荐阅读