如何在 chartjs 中为同一组数据添加多个标签?

How to add several labels to the same set of data in chartjs?

我正在制作一个简单的仪表板,其中有一个显示公司订单量的条形图。 它显示了过去一周每天的订购数量、今天的数量以及接下来几天的预定订单数量。

我正在使用颜色来区分这 3 个时刻中的每一个时刻,但我找不到一个解决方案来拥有 3 个标签,每个标签都有正确的颜色(蓝色代表 [=17=,橙色代表 'today',灰色表示 'scheduled')。

link for current bar chart, as I still don't have enough points

您可以为此使用 generateLabels 函数:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1,
      backgroundColor: ['lightblue', 'lightblue', 'lightblue', 'orange', 'orange', 'gray']
    }]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          generateLabels: () => {
            return [{
                datasetIndex: 0, // Since its all 1 dataset just hide if it gets clicked, remove this line for legend click to do nothing
                text: 'Last week',
                fillStyle: 'lightBlue',
                strokeStyle: 'lightBlue'
              },
              {
                datasetIndex: 0, // Since its all 1 dataset just hide if it gets clicked, remove this line for legend click to do nothing
                text: 'Today',
                fillStyle: 'orange',
                strokeStyle: 'orange'
              },
              {
                datasetIndex: 0, // Since its all 1 dataset just hide if it gets clicked, remove this line for legend click to do nothing
                text: 'Scheduled',
                fillStyle: 'grey',
                strokeStyle: 'grey'
              }
            ];
          }
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>