score:11
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
}
}]
}
}
});
Source: stackoverflow.com
Related Query
- Chart Js change text label orientation on Ox axis
- Chart Js Change Label orientation on x-Axis for Line Charts
- Chart Js reduce text size for label on X axis
- How to change text colour of specific labels of axis in Chart JS?
- I am using chart js to draw a chart. I did everything right but i don't know why the x axis and y axis label is not comming in chart. code below
- ChartJS fails to render one of the lines in cartesian chart following update after change to max Y axis label value
- chartjs datalabels change font and color of text displaying inside pie chart
- show label in tooltip but not in x axis for chartjs line chart
- How do I change the 'months' language displayed on the date axis in Chart JS?
- Chartjs change the specific label color in x axis in callback function
- How to hide the y axis and x axis line and label in my bar chart for chart.js
- Adding custom text to Bar Chart label values using Chart.js
- Change Axis Line color in Chart created using chart.js
- How to change the label and grid line position on a timeseries chart in Chart.js 3?
- Change label color Y and X axis chart.js
- how to label axis within radar chart with chart.js
- display vertical axis label in line chart using chart.js
- chart.js change size of label of radar chart
- How to stop axis label from being cut off in chart JS?
- How to change default label of each bubble in bubble chart using chartjs-plugin-datalabels
- How to rotate the Label text in doughnut chart slice vertically in chart.js canvas, Angular 12?
- show text in both y axis in dual axis chart js
- Chart with Time axis only displaying first grid line and tick label (unitStepSize)
- Move chart x axis label and borders
- How to change orientation of the main y-axis label in charts.js?
- VueJS + Chartjs - Chart only renders after code change
- How to add custom text inside the bar and how to reduce the step size in y axis in chart js( Bar chart )
- Chart.js bar chart change the label position X-axis
- ChartJS - change chart type by changing y-axis Label
- How to change label color of ng2 chart in angular
More Query from same tag
- Vue Chart JS options aren't used
- ChartJs: HorizontalBar Missing Background Colours
- Cant change labels in Chart.js 2.0 Beta
- Multi- Line title in chart.js not working
- Chart.js using json data from MySQL
- how to show chart using chart js
- How do I trigger a clickable event on my chart data
- Does ChartJS supports Jquery 3.4.1
- Chart.js Radar Not Displaying Data Values
- How can i create a background of moving graphs like chartsjs?
- Chart.JS removing data stuck in loop
- I want to put bar of different color by the values in chart.js
- How pass a variable from code behind to javascript
- react-chartjs-2 time scale dates not formatting
- Google Charts, HighCharts or ChartJS Dual Axis Gantt Chart and Line Chart Visualization
- ChartJS horizontal bar with numbers on both scales
- Foreground chart by mouse
- How to change the Y-axis values from numbers to strings in Chart.js?
- Do not draw line on condition in ChartJS line chart
- Show 'No data' in Pie when there is no data using VueJS and ChartJS?
- Update chart.js after form submission and page reload
- highlightFill for radar charts in chartJS
- ChartJS - Adding legend title into tooltip title
- how do I change the textsize in of doughnut in react-chartjs-2?
- Chart.js scatter/bubble pointstyle custom text
- Angular 2 Chart.js and NG2-Charts Not Binding Data Objects After Updates To Project
- How to determine chart type inside 'chart.js' pluginservice
- Hover/click area in filled line chart in chart.js
- chart.js won't display the chart in IE
- Manually display tooltip Chart.js