[Chartjs]-Chartjs defaults deprecation warning

5👍

The correct syntax for globally changing the bar categoryPercentage is the following:

Chart.defaults.global.datasets.bar.categoryPercentage = 0.95;

And here’s a working sample:

Chart.defaults.global.datasets.bar.categoryPercentage = 0.95;

var canvas = document.getElementById('myChart');
var data = {
    labels: ["A", "B", "C", "D", "E"],
    datasets: [{
            label: "Occurrences", 
            data: [3, 5, 2, 4, 6],
            fill: false,
            backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)"],
            borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)"],
            borderWidth: 1
        }]
};
var option = {
	scales: {
  	yAxes:[{
        ticks: {
          beginAtZero: true
        }
    }]
  }
};

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

To find out about other valid options contained in Chart.defaults, simply log it to the console (console.log(Chart.defaults)) and search for the option name.

0👍

You don’t need to set it globally, I actually recommend you to set it for each chart according to documentation.

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

var data = {
  labels: ["A", "B", "C", "D", "E"],
  datasets: [{
    label: "Occurrences",
    data: [3, 5, 2, 4, 6],
    fill: false,
    backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)"],
    borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)"],
    borderWidth: 1
  }]
};

var option = {
  datasets: {
    bar: {
      categoryPercentage: 0.95
    }
  },
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }]
  }
};

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

Leave a comment