Harnish
Harnish

Reputation: 101

Tilting the labels of the x axis to some degrees in chart.js

I am constructing a chart using chart.js. Is there any simple method to tilt the x axis labels to some degrees? There was a lot of things done to make it tilt in Chart Js change text label orientation on Ox axis. Anything simple can be done?

Upvotes: 1

Views: 2902

Answers (1)

potatopeelings
potatopeelings

Reputation: 41065

You can extend the chart to do this - you override the calculateXLabelRotation method of the scale object.


Preview(s)

enter image description here


Script

Chart.types.Line.extend({
  name: "LineAlt",
  initialize: function() {
    Chart.types.Line.prototype.initialize.apply(this, arguments);

    var scale = this.scale;
    var chart = this.chart;
    scale.calculateXLabelRotation = function() {
      var originalLabelWidth = Chart.helpers.longestText(chart.ctx, scale.font, scale.xLabels);
      var firstWidth = ctx.measureText(scale.xLabels[0]).width;
      var firstRotated = Math.cos(Chart.helpers.radians(scale.xLabelRotation)) * firstWidth;
      scale.xLabelRotation = 45;
      scale.endPoint -= Math.sin(Chart.helpers.radians(scale.xLabelRotation)) * originalLabelWidth + 3;
      scale.xScalePaddingLeft = firstRotated + scale.fontSize / 2;
    }
    this.scale.fit();
  }
});

and then

...
new Chart(ctx).LineAlt(data);

Fiddle - http://jsfiddle.net/vvLttjz4/

Upvotes: 2

Related Questions