Dror Aharon
Dror Aharon

Reputation: 153

Chartjs: How to create padding between ticks and scale label

I'm using chartjs-node to create a graph, and I use a label for the Y-axis.

My problem is that the distance between the Y-axes ticks and label is minimal and does not look good. I've gone over the docs and couldn't find anything all that useful for this scenario... There's an option under options -> scales -> yAxes -> ticks -> padding but it doesn't give the desired effect.

Currently I have a workaround under options -> scales -> yAxes -> ticks -> callback I manually insert spaces: callback: (val) => ` ${val}%`

This works, but obviously is not the correct usage, and I believe that if the scale is linear this approach will prohibit me from using some of the features available with a linear scale.

Anyone knows how I can create the separation between the ticks and the label in a more elegant way?

Upvotes: 3

Views: 17736

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

This can be achieved using afterFit callback function of y-axis :

scales: {
   yAxes: [{
      afterFit: function(scale) {
         scale.width = 80 //<-- set value as you wish 
      },
      ...
   }]
}

ɪɴ ᴀᴄᴛɪᴏɴ

var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar'],
      datasets: [{
         label: 'LINE',
         data: [3, 2, 4],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      responsive: false,
      scales: {
         yAxes: [{
            afterFit: function(scale) {
               scale.width = 80  //<-- set value as you wish 
            },
            scaleLabel: {
               display: true,
               labelString: 'y-axis label',
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" height="180"></canvas>

Upvotes: 11

Related Questions