[Chartjs]-Setting Common labels and background color common for all the charts in ChartJs

2👍

If speaking technically then yes, there is a way. Though it­‘s not recommended, as that­‘s not how ChartJS meant to work, therefore no built-in functionality either.

To accomplish this you would rather go for kind of a hacky solution, which is to use a plugin, like the following :

Chart.plugins.register({
   beforeInit: function(chart) {
      chart.data.labels = ['Signed', 'Not Signed'];
      chart.data.datasets[0].backgroundColor = ['#1abc9c', '#34495e'];
   }
});

* add this at the beginning of your script

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

Chart.plugins.register({
   beforeInit: function(chart) {
      chart.data.labels = ['Signed', 'Not Signed'];
      chart.data.datasets[0].backgroundColor = ['#1abc9c', '#34495e'];
   }
});

var ctx1 = document.getElementById("pieChart1");
var ctx2 = document.getElementById("pieChart2");

var data1 = {
   datasets: [{
      data: [10, 25],
   }]
};

var data2 = {
   datasets: [{
      data: [15, 2]
   }]
};

var myPieChart1 = new Chart(ctx1, {
   type: 'pie',
   data: data1
});

var myPieChart2 = new Chart(ctx2, {
   type: 'pie',
   data: data2
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="pieChart1" width="500px" height="300"></canvas>
<canvas id="pieChart2" width="500px" height="300"></canvas>

Leave a comment