如何在每个堆叠的条形图单元格中设置不同的颜色?

时间:2020-11-03 14:18:27

标签: angularjs chart.js

enter image description here

我正在尝试创建这样的图表。以下是我的图表代码。但是,我无法在第二栏中设置其他颜色。第一个栏中的第一种颜色设置在第二个栏中。

self.chart = {
        type: 'horizontal-bar',
        options: {
          responsive: true,
          maintainAspectRatio: false,
          tooltips: {
            enabled: true,
            callbacks: {
              label: function (tooltipItem, _) {
                return $filter('number')(tooltipItem.xLabel);
              }
            }
          },
          events: ['click', 'mousemove'],
          hover: {
            onHover: function(item, chartElement) {
              item.target.style.cursor = chartElement[0] ? 'pointer' : 'default'; 
            }
          },
          scales: {
            xAxes: [{
              scaleLabel: {
                stacked: true,
                display: true,
                labelString: "Test"
              },
              ticks: {
                stacked: true,
                beginAtZero: true,
                maxRotation: 0,
                minRotation: 0,
                callback: function (value) {
                  return $filter('number')(value);
                }
              }
            }]
          }
        },
        data: [[2,12], [5]],
        labels: labels,
        colors: [chartBlue, chartGreen],
        datasetOverride: [{ stack: 1, fill: false }, { stack: 1, fill: false }]
      }

这是我得到的结果。

enter image description here

我需要在第二栏中设置其他颜色(例如黄色)。

2 个答案:

答案 0 :(得分:0)

使用colors定义数据集的颜色。用两种颜色定义两个数据集。 data中有两个数组,因此有两个数据集,这就是为什么看不到其他颜色的原因。 您需要第三种颜色的第三种数据集,在不需要条形的标签上带有0

查看以下示例(Working example at JSBin):

var config = {
  type: 'bar',
  data: {
    labels: ["January", "February", "March"],
    datasets: [{
      label: 'Dataset 1',
      backgroundColor: 'black',
      data: [0, 8, 4]      
    }, {
      label: 'Dataset 2',
      backgroundColor: "red",
      data: [6, 2, 8],
    }, {
      label: 'Dataset 3',
      backgroundColor: "blue",
      data: [3, 0, 0]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

答案 1 :(得分:-1)

您是否尝试添加更多数据?

 data: [[2,12], [5], [1], [4], [3]],
 labels: labels,
 colors: [chartBlue, chartGreen],

尝试一下,看看图表发生了什么:)