accelerate
accelerate

Reputation: 1353

ChartJS align axis label to the top

Is there a way in ChartJS / react-chartjs-2 to align the Y-Axis title to the top of the axis instead of the default vertical alignment?

In other words, instead of this: enter image description here

I want this: enter image description here

My basic configuration for the Y-axis is as follows:

yAxes: [
  {
    scaleLabel: {
      display: true,
      labelString: '$ USD'
    }
  }
]

Upvotes: 2

Views: 2053

Answers (1)

Kunal Khivensara
Kunal Khivensara

Reputation: 1669

I am not sure if there is built-in support for this requirement in Chart.js however you can fill the ctx with any value from the code shown below. Please adjust the xOffset and yOffset value as per your need. Fiddle -> http://jsfiddle.net/Lzo5g01n/8/

animation: {
      duration: 1,
      onComplete: function() {
        var controller = this.chart.controller;
        var chart = controller.chart;
        var yAxis = controller.scales['y-axis-0'];
        var xOffset = chart.width - (chart.width - 5);
        var yOffset = chart.height - (chart.height - 18);
        ctx.fillText('$USD', xOffset, yOffset);
      }
    }

With the above code there is one issue that the label goes off on hovering over the bar.

This new code may help to resolve the issue -> http://jsfiddle.net/moz73qep/3/

var myBarExtend = Chart.controllers.bar.prototype.draw;

Chart.helpers.extend(Chart.controllers.bar.prototype, {
    draw: function () {
      myBarExtend.apply(this, arguments);   
      var controller = this.chart.controller;
        var chart = controller.chart;
        var yAxis = controller.scales['y-axis-0'];
        var xOffset = chart.width - (chart.width - 5);
        var yOffset = chart.height - (chart.height - 18);
        ctx.fillText('$USD', xOffset, yOffset);
    } });

Upvotes: 1

Related Questions