带动态颜色的ChartJS

时间:2017-09-08 14:07:59

标签: chart.js

我看到你的帖子, 而不只是" Stock"在左边,无论如何要为每个条形图放置一个单独的标签,例如沿y轴向下移动18,82,22,80? 以下是我所指的链接...... ChartJS bar chart with legend which corresponds to each bar

1 个答案:

答案 0 :(得分:2)

您正在寻找以下内容:



var chart = new Chart(ctx, {
   type: 'horizontalBar',
   data: {
      labels: [18, 82, 22, 80],
      datasets: [{
         data: [1, 2, 3, 4],
         backgroundColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff'],
         borderColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff']
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      },
      legend: {
         labels: {
            generateLabels: function(chart) {
               var labels = chart.data.labels;
               var dataset = chart.data.datasets[0];
               var legend = labels.map(function(label, index) {
                  return {
                     datasetIndex: 0,
                     text: label,
                     fillStyle: dataset.backgroundColor[index],
                     strokeStyle: dataset.borderColor[index],
                     lineWidth: 1
                  }
               });
               return legend;
            }
         }
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
&#13;
&#13;
&#13;