score:11

Accepted answer

you would need to extend the scale class and override the calculatexlabelrotation method to use a user inputted rotation rather than trying to work it out it's self. if you do this you would then need to extend the bar or line chart and override the init method to make use of this scale class. (or you could make these changes directly to the scale, bar and line classes and then no need to override).

so first extend scale class and make it use a user defined option

var helpers = chart.helpers;
chart.myscale = chart.scale.extend({
    calculatexlabelrotation: function() {
        //get the width of each grid by calculating the difference
        //between x offsets between 0 and 1.

        this.ctx.font = this.font;

        var firstwidth = this.ctx.measuretext(this.xlabels[0]).width,
            lastwidth = this.ctx.measuretext(this.xlabels[this.xlabels.length - 1]).width,
            firstrotated,
            lastrotated;


        this.xscalepaddingright = lastwidth / 2 + 3;
        this.xscalepaddingleft = (firstwidth / 2 > this.ylabelwidth + 10) ? firstwidth / 2 : this.ylabelwidth + 10;

        this.xlabelrotation = 0;
        if (this.display) {
            var originallabelwidth = helpers.longesttext(this.ctx, this.font, this.xlabels),
                cosrotation,
                firstrotatedwidth;
            this.xlabelwidth = originallabelwidth;
            //allow 3 pixels x2 padding either side for label readability
            var xgridwidth = math.floor(this.calculatex(1) - this.calculatex(0)) - 6;
            //check if option is set if so use that
            if (this.overriderotation) {
                // do the same as before but manualy set the rotation rather than looping
                 this.xlabelrotation = this.overriderotation;
                 cosrotation = math.cos(helpers.radians(this.xlabelrotation));
                  // we're right aligning the text now.
                    if (firstrotated + this.fontsize / 2 > this.ylabelwidth + 8) {
                        this.xscalepaddingleft = firstrotated + this.fontsize / 2;
                    }
                    this.xscalepaddingright = this.fontsize / 2;
                    this.xlabelwidth = cosrotation * originallabelwidth;
            } else {
                //max label rotate should be 90 - also act as a loop counter
                while ((this.xlabelwidth > xgridwidth && this.xlabelrotation === 0) || (this.xlabelwidth > xgridwidth && this.xlabelrotation <= 90 && this.xlabelrotation > 0)) {
                    cosrotation = math.cos(helpers.radians(this.xlabelrotation));

                    firstrotated = cosrotation * firstwidth;
                    lastrotated = cosrotation * lastwidth;

                    // we're right aligning the text now.
                    if (firstrotated + this.fontsize / 2 > this.ylabelwidth + 8) {
                        this.xscalepaddingleft = firstrotated + this.fontsize / 2;
                    }
                    this.xscalepaddingright = this.fontsize / 2;


                    this.xlabelrotation++;
                    this.xlabelwidth = cosrotation * originallabelwidth;

                }
            }
            if (this.xlabelrotation > 0) {
                this.endpoint -= math.sin(helpers.radians(this.xlabelrotation)) * originallabelwidth + 3;
            }
        } else {
            this.xlabelwidth = 0;
            this.xscalepaddingright = this.padding;
            this.xscalepaddingleft = this.padding;
        }

    },

});

then in the extend the bar class to create a new graph type and override the init method to use the new

chart.types.bar.extend({
    name: "mybar",
    initialize: function(data) {

        //expose options as a scope variable here so we can access it in the scaleclass
        var options = this.options;

        this.scaleclass = chart.myscale.extend({
            overriderotation: options.overriderotation,
            offsetgridlines: true,
            calculatebarx: function(datasetcount, datasetindex, barindex) {
                //reusable method for calculating the xposition of a given bar based on datasetindex & width of the bar
                var xwidth = this.calculatebasewidth(),
                    xabsolute = this.calculatex(barindex) - (xwidth / 2),
                    barwidth = this.calculatebarwidth(datasetcount);

                return xabsolute + (barwidth * datasetindex) + (datasetindex * options.bardatasetspacing) + barwidth / 2;
            },
            calculatebasewidth: function() {
                return (this.calculatex(1) - this.calculatex(0)) - (2 * options.barvaluespacing);
            },
            calculatebarwidth: function(datasetcount) {
                //the padding between datasets is to the right of each bar, providing that there are more than 1 dataset
                var basewidth = this.calculatebasewidth() - ((datasetcount - 1) * options.bardatasetspacing);

                return (basewidth / datasetcount);
            }
        });

        this.datasets = [];

        //set up tooltip events on the chart
        if (this.options.showtooltips) {
            helpers.bindevents(this, this.options.tooltipevents, function(evt) {
                var activebars = (evt.type !== 'mouseout') ? this.getbarsatevent(evt) : [];

                this.eachbars(function(bar) {
                    bar.restore(['fillcolor', 'strokecolor']);
                });
                helpers.each(activebars, function(activebar) {
                    activebar.fillcolor = activebar.highlightfill;
                    activebar.strokecolor = activebar.highlightstroke;
                });
                this.showtooltip(activebars);
            });
        }

        //declare the extension of the default point, to cater for the options passed in to the constructor
        this.barclass = chart.rectangle.extend({
            strokewidth: this.options.barstrokewidth,
            showstroke: this.options.barshowstroke,
            ctx: this.chart.ctx
        });

        //iterate through each of the datasets, and build this into a property of the chart
        helpers.each(data.datasets, function(dataset, datasetindex) {

            var datasetobject = {
                label: dataset.label || null,
                fillcolor: dataset.fillcolor,
                strokecolor: dataset.strokecolor,
                bars: []
            };

            this.datasets.push(datasetobject);

            helpers.each(dataset.data, function(datapoint, index) {
                //add a new point for each piece of data, passing any required data to draw.
                datasetobject.bars.push(new this.barclass({
                    value: datapoint,
                    label: data.labels[index],
                    datasetlabel: dataset.label,
                    strokecolor: dataset.strokecolor,
                    fillcolor: dataset.fillcolor,
                    highlightfill: dataset.highlightfill || dataset.fillcolor,
                    highlightstroke: dataset.highlightstroke || dataset.strokecolor
                }));
            }, this);

        }, this);

        this.buildscale(data.labels);

        this.barclass.prototype.base = this.scale.endpoint;

        this.eachbars(function(bar, index, datasetindex) {
            helpers.extend(bar, {
                width: this.scale.calculatebarwidth(this.datasets.length),
                x: this.scale.calculatebarx(this.datasets.length, datasetindex, index),
                y: this.scale.endpoint
            });
            bar.save();
        }, this);

        this.render();
    },
});

now you can declare a chart using this chart type and pass in the option overriderotation

here is a fiddle example http://jsfiddle.net/leighking2/ye3usuhu/

and a snippet

var helpers = chart.helpers;
chart.myscale = chart.scale.extend({
    calculatexlabelrotation: function() {
        //get the width of each grid by calculating the difference
        //between x offsets between 0 and 1.

        this.ctx.font = this.font;

        var firstwidth = this.ctx.measuretext(this.xlabels[0]).width,
            lastwidth = this.ctx.measuretext(this.xlabels[this.xlabels.length - 1]).width,
            firstrotated,
            lastrotated;


        this.xscalepaddingright = lastwidth / 2 + 3;
        this.xscalepaddingleft = (firstwidth / 2 > this.ylabelwidth + 10) ? firstwidth / 2 : this.ylabelwidth + 10;

        this.xlabelrotation = 0;
        if (this.display) {
            var originallabelwidth = helpers.longesttext(this.ctx, this.font, this.xlabels),
                cosrotation,
                firstrotatedwidth;
            this.xlabelwidth = originallabelwidth;
            //allow 3 pixels x2 padding either side for label readability
            var xgridwidth = math.floor(this.calculatex(1) - this.calculatex(0)) - 6;
            
            if (this.overriderotation) {
                 this.xlabelrotation = this.overriderotation;
                 cosrotation = math.cos(helpers.radians(this.xlabelrotation));
                  // we're right aligning the text now.
                    if (firstrotated + this.fontsize / 2 > this.ylabelwidth + 8) {
                        this.xscalepaddingleft = firstrotated + this.fontsize / 2;
                    }
                    this.xscalepaddingright = this.fontsize / 2;
                    this.xlabelwidth = cosrotation * originallabelwidth;
            } else {
                //max label rotate should be 90 - also act as a loop counter
                while ((this.xlabelwidth > xgridwidth && this.xlabelrotation === 0) || (this.xlabelwidth > xgridwidth && this.xlabelrotation <= 90 && this.xlabelrotation > 0)) {
                    cosrotation = math.cos(helpers.radians(this.xlabelrotation));

                    firstrotated = cosrotation * firstwidth;
                    lastrotated = cosrotation * lastwidth;

                    // we're right aligning the text now.
                    if (firstrotated + this.fontsize / 2 > this.ylabelwidth + 8) {
                        this.xscalepaddingleft = firstrotated + this.fontsize / 2;
                    }
                    this.xscalepaddingright = this.fontsize / 2;


                    this.xlabelrotation++;
                    this.xlabelwidth = cosrotation * originallabelwidth;

                }
            }
            if (this.xlabelrotation > 0) {
                this.endpoint -= math.sin(helpers.radians(this.xlabelrotation)) * originallabelwidth + 3;
            }
        } else {
            this.xlabelwidth = 0;
            this.xscalepaddingright = this.padding;
            this.xscalepaddingleft = this.padding;
        }

    },

});

chart.types.bar.extend({
    name: "mybar",
    initialize: function(data) {

        //expose options as a scope variable here so we can access it in the scaleclass
        var options = this.options;

        this.scaleclass = chart.myscale.extend({
            overriderotation: options.overriderotation,
            offsetgridlines: true,
            calculatebarx: function(datasetcount, datasetindex, barindex) {
                //reusable method for calculating the xposition of a given bar based on datasetindex & width of the bar
                var xwidth = this.calculatebasewidth(),
                    xabsolute = this.calculatex(barindex) - (xwidth / 2),
                    barwidth = this.calculatebarwidth(datasetcount);

                return xabsolute + (barwidth * datasetindex) + (datasetindex * options.bardatasetspacing) + barwidth / 2;
            },
            calculatebasewidth: function() {
                return (this.calculatex(1) - this.calculatex(0)) - (2 * options.barvaluespacing);
            },
            calculatebarwidth: function(datasetcount) {
                //the padding between datasets is to the right of each bar, providing that there are more than 1 dataset
                var basewidth = this.calculatebasewidth() - ((datasetcount - 1) * options.bardatasetspacing);

                return (basewidth / datasetcount);
            }
        });

        this.datasets = [];

        //set up tooltip events on the chart
        if (this.options.showtooltips) {
            helpers.bindevents(this, this.options.tooltipevents, function(evt) {
                var activebars = (evt.type !== 'mouseout') ? this.getbarsatevent(evt) : [];

                this.eachbars(function(bar) {
                    bar.restore(['fillcolor', 'strokecolor']);
                });
                helpers.each(activebars, function(activebar) {
                    activebar.fillcolor = activebar.highlightfill;
                    activebar.strokecolor = activebar.highlightstroke;
                });
                this.showtooltip(activebars);
            });
        }

        //declare the extension of the default point, to cater for the options passed in to the constructor
        this.barclass = chart.rectangle.extend({
            strokewidth: this.options.barstrokewidth,
            showstroke: this.options.barshowstroke,
            ctx: this.chart.ctx
        });

        //iterate through each of the datasets, and build this into a property of the chart
        helpers.each(data.datasets, function(dataset, datasetindex) {

            var datasetobject = {
                label: dataset.label || null,
                fillcolor: dataset.fillcolor,
                strokecolor: dataset.strokecolor,
                bars: []
            };

            this.datasets.push(datasetobject);

            helpers.each(dataset.data, function(datapoint, index) {
                //add a new point for each piece of data, passing any required data to draw.
                datasetobject.bars.push(new this.barclass({
                    value: datapoint,
                    label: data.labels[index],
                    datasetlabel: dataset.label,
                    strokecolor: dataset.strokecolor,
                    fillcolor: dataset.fillcolor,
                    highlightfill: dataset.highlightfill || dataset.fillcolor,
                    highlightstroke: dataset.highlightstroke || dataset.strokecolor
                }));
            }, this);

        }, this);

        this.buildscale(data.labels);

        this.barclass.prototype.base = this.scale.endpoint;

        this.eachbars(function(bar, index, datasetindex) {
            helpers.extend(bar, {
                width: this.scale.calculatebarwidth(this.datasets.length),
                x: this.scale.calculatebarx(this.datasets.length, datasetindex, index),
                y: this.scale.endpoint
            });
            bar.save();
        }, this);

        this.render();
    },
});



var randomscalingfactor = function() {
    return math.round(math.random() * 100)
};

var barchartdata = {
    labels: ["january", "february", "march", "april", "may", "june", "july"],
    datasets: [{
        fillcolor: "rgba(220,220,220,0.5)",
        strokecolor: "rgba(220,220,220,0.8)",
        highlightfill: "rgba(220,220,220,0.75)",
        highlightstroke: "rgba(220,220,220,1)",
        data: [randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor()]
    }, {
        fillcolor: "rgba(151,187,205,0.5)",
        strokecolor: "rgba(151,187,205,0.8)",
        highlightfill: "rgba(151,187,205,0.75)",
        highlightstroke: "rgba(151,187,205,1)",
        data: [randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor()]
    }, {
        fillcolor: "rgba(15,18,20,0.5)",
        strokecolor: "rgba(15,18,20,0.8)",
        highlightfill: "rgba(15,18,20,0.75)",
        highlightstroke: "rgba(15,18,20,1)",
        data: [randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor()]
    }]

}
window.onload = function() {
    var ctx = document.getelementbyid("canvas").getcontext("2d");
    window.mybar = new chart(ctx).mybar(barchartdata, {
        overriderotation: 30
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/1.0.1/chart.js"></script>

    <canvas id="canvas" height="150" width="300"></canvas>

score:0

note that for chart.js 3.x the way of specifying the axis scale options has changed: see https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales

consequently in the above answer for 2.x you need to remove the square brackets like this:

var mychart = new chart(ctx, {
  type: 'bar',
  data: chartdata,
  options: {
    scales: {
      xaxes: {
        ticks: {
          autoskip: false,
          maxrotation: 90,
          minrotation: 90
        }
      }
    }
  }
});

score:25

if you are using chart.js 2.x, just set maxrotation: 90 and minrotation: 90 in ticks options. it works for me! and if you want to all x-labels, you may want to set autoskip: false. the following is an example.

var mychart = new chart(ctx, {
  type: 'bar',
  data: chartdata,
  options: {
    scales: {
      xaxes: [{
        ticks: {
          autoskip: false,
          maxrotation: 90,
          minrotation: 90
        }
      }]
    }
  }
});

Related Query

More Query from same tag