如何更改chartjs中图例的颜色,并能够再添加一个图例?

时间:2017-06-04 09:02:40

标签: javascript chart.js

我想更改图例的颜色,因为我想要不同的颜色来表示不同的情况。但现在图例只使用我在条形图上设置的第一种颜色。

我也想问一下,是否可以设置一个传奇?像粉红色是针对情况A,蓝色是针对B?

Here is the link:

Code is here 有人可以帮忙吗?非常感谢你。

1 个答案:

答案 0 :(得分:4)

要设置更多图例,您需要添加多个数据集。每个数据集将代表一个图例,并且图例颜色将根据数据集背景颜色自动设置。

Chart.plugins.register({
   beforeDraw: function(c) {
      var legends = c.legend.legendItems;
      legends.forEach(function(e) {
         e.fillStyle = '#07C';
      });
   }
});

var canvas = document.getElementById('myChart');

var data = {
   labels: ["January", "February", "March", "April", "May", "June"],
   datasets: [{
      label: "My First dataset",
      backgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 20, 81, 56, 55],
   }, {
      label: "My Second dataset",
      backgroundColor: "rgba(25,25,255,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 20, 81, 56, 55],
   }]
};

var option = {
   scales: {
      xAxes: [{
         stacked: true
      }],
      yAxes: [{
         stacked: true,
         gridLines: {
            display: true,
            color: "rgba(255,99,132,0.2)"
         }
      }]
   }
};

var myBarChart = Chart.Bar(canvas, {
   data: data,
   options: option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>