定期更改同一数据集的某些条形的颜色 Chartjs

我正在尝试在我的条形图上每五个条形更改同一数据集的两个条形的颜色。


我想要这样的东西:红色红色蓝色蓝色蓝色蓝色红色红色蓝色...


目前我有以下代码:


    var chart = new Chart(ctx, {

    type: 'bar',

    data: {

        labels: labels,

        datasets: [{

            label: 'dataset1',

            fill: false,

            // i want this to be red 2 times every 5 bars

            backgroundColor: 'rgb(255,204,100)',

            borderColor: 'rgb(255,204,100)',

            hoverBackgroundColor: 'rgb(156,94,0)',

            hoverBorderColor: 'rgb(156,94,0)',

            data: data

        } ]

    },

    options: {

        responsive: true

        //more code...

    }

});


动漫人物
浏览 42回答 1
1回答

湖上湖

您可以只设置为与条形图数据具有相同长度的颜色数组。backgroundColor例如:const config = {&nbsp; type: 'bar',&nbsp; data: {&nbsp; &nbsp; labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],&nbsp; &nbsp; datasets: [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; label: 'Dataset 1',&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: ['red', 'red', 'blue', 'blue', 'blue', 'red', 'red'],&nbsp; &nbsp; &nbsp; &nbsp; borderWidth: 1,&nbsp; &nbsp; &nbsp; &nbsp; data: [-3, 30, -10, 33, -9, 14, -11],&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ],&nbsp; },&nbsp; options: {&nbsp; &nbsp; legend: {&nbsp; &nbsp; &nbsp; display: false&nbsp; &nbsp; }&nbsp; }};const ctx = document.getElementById('canvas').getContext('2d');new Chart(ctx, config);<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script><body>&nbsp; &nbsp; <canvas id="canvas" width="600" height="400"></canvas></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript