如何在chartjs中更改图例的颜色并能够添加更多图例? [英] How to change the color of legend in chartjs and be able to add one more legend?

查看:265
本文介绍了如何在chartjs中更改图例的颜色并能够添加更多图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change the color of legend, because I want different colors to represent different situations.But now the legend uses just the first color I set on the bar chart.

我还想问一问,它还能设置一个图例吗?比如粉红色代表情况A,蓝色代表B?

I also want to ask, is it able to set one more legend?Like pink is for situationA, blue for B?

Here is the link:

代码在这里
有人可以帮忙吗?谢谢你。

Code is here Can anyone help?Thank you so much.

推荐答案

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

To set more legends, you need to add multiple datasets. Each dataset will represent one legend and the legend­'s color will automatically be set according to the dataset­'s background color.

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>

这篇关于如何在chartjs中更改图例的颜色并能够添加更多图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆