【问题标题】:Change color of certain bars of same dataset periodically Chartjs定期更改同一数据集的某些条形图的颜色 Chartjs
【发布时间】:2020-06-10 16:23:54
【问题描述】:

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

我想要类似的东西:红色红色蓝色蓝色蓝色蓝色蓝色红色红色蓝色......

目前我有以下代码:

    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...
    }
});

【问题讨论】:

标签: javascript node.js express chart.js bar-chart


【解决方案1】:

您可以将backgroundColor 设置为与条形图数据长度相同的颜色数组。

例如:

const config = {
  type: 'bar',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [
      {
        label: 'Dataset 1',
        backgroundColor: ['red', 'red', 'blue', 'blue', 'blue', 'red', 'red'],
        borderWidth: 1,
        data: [-3, 30, -10, 33, -9, 14, -11],
      }
    ],
  },
  options: {
    legend: {
      display: false
    }
  }
};

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>
    <canvas id="canvas" width="600" height="400"></canvas>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2022-11-03
    • 2012-10-18
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多