[Chartjs]-Chart.js – How to create a different global configuration between the x axis and the y axis

2👍

Chart.defaults contains chart type specific sections that include the scales option. You can use console.log(Chart.defaults) to find out how it looks like.

Chart.defaults.bar for example is defined as follows:

"bar": {
  "hover": {
    "mode": "label"
  },
  "scales": {
    "xAxes": [{
      "type": "category",
      "offset": true,
      "gridLines": {
        "offsetGridLines": true
      }
    }],
    "yAxes": [{
      "type": "linear"
    }]
  }
}

If the parent object of a nested property is already defined, you can directly assign its value.

Chart.defaults.bar.scales.xAxes[0].gridLines.drawOnChartArea = false;

If however the parent object is not yet defined, you need to assign the property together with its parent object or object hierarchy. When you do this, make sure to also take over previously existing default values.

Chart.defaults.bar.legend = { display: false };

Please have a look at below code sample.

Chart.defaults.bar.legend = {
  display: false
};
Chart.defaults.bar.scales.xAxes[0].gridLines.drawOnChartArea = false;
Chart.defaults.bar.scales.yAxes[0] = {
  type: 'linear',
  gridLines: {
    drawOnChartArea: false
  },
  ticks: {
    beginAtZero: true
  }
};

new Chart(document.getElementById("myChart"), {
  type: 'bar',
  data: {
    labels: ["A", "B", "C", "D"],
    datasets: [{
      data: [25, 18, 8, 13],
      backgroundColor: ['red', 'blue', 'green', 'orange']
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script> 
<canvas id="myChart" height="90"></canvas>

Leave a comment