[Chartjs]-Tilting the labels of the x axis to some degrees in chart.js

2👍

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/

Leave a comment