score:3
this answer is for chartjs 1.x for an answer covering 2.x take a look at the great answer from @tabetomo https://stackoverflow.com/a/39706986/2737978
using the same method as in the previous answer the only thing that needs to changed is the extension of the graph type. this time it is extending the line chart and the set-up is a little different as the line charts scale is created in the build scale so this time it is buildscale
is overridden so that the custom scale is used and the new option overriderotation
can be passed in. initialize
is also overridden but only so that the super initialize can be called and get the ball rolling on building the graph.
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.line.extend({
name: "myline",
initialize: function(data) {
chart.types.line.prototype.initialize.apply(this, arguments);
},
buildscale: function(labels) {
var self = this;
var datatotal = function() {
var values = [];
self.eachpoints(function(point) {
values.push(point.value);
});
return values;
};
var scaleoptions = {
templatestring: this.options.scalelabel,
height: this.chart.height,
width: this.chart.width,
ctx: this.chart.ctx,
textcolor: this.options.scalefontcolor,
offsetgridlines: this.options.offsetgridlines,
fontsize: this.options.scalefontsize,
fontstyle: this.options.scalefontstyle,
fontfamily: this.options.scalefontfamily,
valuescount: labels.length,
beginatzero: this.options.scalebeginatzero,
integersonly: this.options.scaleintegersonly,
calculateyrange: function(currentheight) {
var updatedranges = helpers.calculatescalerange(
datatotal(),
currentheight,
this.fontsize,
this.beginatzero,
this.integersonly
);
helpers.extend(this, updatedranges);
},
xlabels: labels,
font: helpers.fontstring(this.options.scalefontsize, this.options.scalefontstyle, this.options.scalefontfamily),
linewidth: this.options.scalelinewidth,
linecolor: this.options.scalelinecolor,
showhorizontallines: this.options.scaleshowhorizontallines,
showverticallines: this.options.scaleshowverticallines,
gridlinewidth: (this.options.scaleshowgridlines) ? this.options.scalegridlinewidth : 0,
gridlinecolor: (this.options.scaleshowgridlines) ? this.options.scalegridlinecolor : "rgba(0,0,0,0)",
padding: (this.options.showscale) ? 0 : this.options.pointdotradius + this.options.pointdotstrokewidth,
showlabels: this.options.scaleshowlabels,
display: this.options.showscale,
overriderotation: this.options.overriderotation,
};
if (this.options.scaleoverride) {
helpers.extend(scaleoptions, {
calculateyrange: helpers.noop,
steps: this.options.scalesteps,
stepvalue: this.options.scalestepwidth,
min: this.options.scalestartvalue,
max: this.options.scalestartvalue + (this.options.scalesteps * this.options.scalestepwidth)
});
}
this.scale = new chart.myscale(scaleoptions);
},
});
var randomscalingfactor = function() {
return math.round(math.random() * 100)
};
var barchartdata = {
labels: ["january", "february", "march", "april", "may", "june", "july"],
datasets: [{
fillcolor: "rgba(20,20,220,0.2)",
strokecolor: "rgba(20,20,220,1)",
pointcolor: "rgba(20,20,220,1)",
pointstrokecolor: "#fff",
pointhighlightfill: "#fff",
pointhighlightstroke: "rgba(20,20,220,1)",
data: [randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor()]
}, {
fillcolor: "rgba(120,120,120,0.2)",
strokecolor: "rgba(120,220,120,1)",
pointcolor: "rgba(120,120,120,1)",
pointstrokecolor: "#fff",
pointhighlightfill: "#fff",
pointhighlightstroke: "rgba(120,120,120,1)",
data: [randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor()]
}, {
fillcolor: "rgba(220,220,220,0.2)",
strokecolor: "rgba(220,220,220,1)",
pointcolor: "rgba(220,220,220,1)",
pointstrokecolor: "#fff",
pointhighlightfill: "#fff",
pointhighlightstroke: "rgba(220,220,220,1)",
data: [randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor(), randomscalingfactor()]
}]
}
window.onload = function() {
var ctx = document.getelementbyid("canvas").getcontext("2d");
window.mybar = new chart(ctx).myline(barchartdata, {
overriderotation: 90
});
}
<script src="http://www.chartjs.org/assets/chart.min.js"></script>
<canvas id="canvas" height="150" width="300"></canvas>
score:2
here's a slightly more hackier version (quince's answer is better - the following may break if a future implementation of chart.js does calculatexlabelrotation
differently)
the label rotation is calculated by progressively rotating the labels so that they fit between the vertical grid lines - the space between them is calculated using scale.calculatex(1) - scale.calculatex(0)
. we jump in at the right point to force the result of this calculation to be 0 (by making scale.calculatex
return the same value) - this in turn forces the rotation to progress to it's maximum (i.e. 90 degrees)
preview
script
chart.types.line.extend({
name: "linealt",
initialize: function () {
chart.types.line.prototype.initialize.apply(this, arguments);
var scale = this.scale;
var originalcalculatexlabelrotation = scale.calculatexlabelrotation;
var originalxscalepaddingleft = scale.xscalepaddingleft;
scale.calculatexlabelrotation = function () {
var originalcalculatex = scale.calculatex;
scale.calculatex = function () {
return 0;
}
originalcalculatexlabelrotation.apply(this, arguments);
scale.xscalepaddingleft = originalxscalepaddingleft;
scale.calculatex = originalcalculatex;
}
this.scale.fit();
}
});
and then
...
new chart(ctx).linealt(data);
fiddle - http://jsfiddle.net/gc5gdg7e/
score:6
it worked for me on version 3.1.0
var mychart = new chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
x: {
ticks: {
maxrotation: 90,
minrotation: 90
}
}
}
}
})
score:11
for x axis use this
options: {
legend: {
display: false
},
scales: {
xaxes: [
{
ticks: {
autoskip: false,
maxrotation: 0,
minrotation: 0
}
}
]
}
}
and can filter the label with a for
loop:
arraylabels.foreach((date, i) => {
let label = "";
if (i % step == 0 && fecha) {
label = moment(date, "dd/mm").format("dd mmm");
}
labels.push(label);
});
chartoptions.data.labels = labels;
score:172
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 Label orientation on x-Axis for Line Charts
- Chart Js change text label orientation on Ox axis
- show label in tooltip but not in x axis for chartjs line chart
- How to hide the y axis and x axis line and label in my bar chart for chart.js
- how to change Y axis value dynamically based on user input in Chartjs for Line chart?
- 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 space between horizontal (grid) lines for line chart
- display vertical axis label in line chart using chart.js
- Chart Js reduce text size for label on X axis
- Chart.js two y axes line chart tooltip value incorrect for 2nd y axis
- Chart with Time axis only displaying first grid line and tick label (unitStepSize)
- How do you set x and y axis and Title for a line chart using charts.js?
- ChartJS/High Charts Radar chart - Different radial axis labels for each category that appear on hover
- How to start Y Axis Line at 0 from right for negative values in chart js 2?
- Show label for every data point in line chart
- 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: Is there a way to control the font options per line for a multiline axis label
- Line chart plotting multiple points for duplicate data on x and y axis using chart.js
- ChartJS fails to render one of the lines in cartesian chart following update after change to max Y axis label value
- How to change line chart data label to icon or image in chart.js
- Using custom dataformat in chart.js for Multi Axis Line Chart
- Chart.js how to show cursor pointer for labels & legends in line chart
- Chartjs 2 - Stacked bar and unstacked line on same chart with same y axis
- Legends for line charts in Chart.js
- How to add second Y-axis for Bar and Line chart in Chart.js?
- chart.js Line chart with different background colors for each section
- Chart JS - set start of week for x axis time series
- Chart js. How to change font styles for "labels" array?
- Show X axis on top and bottom in line chart rendered with Chart.js 2.4.0
More Query from same tag
- Weird time formating with chart.js and moment.js
- Chartjs: update the min and maximum of the yaxes ticks on a click
- How to hide the legend in chart.js in a react project?
- How to group chart labels together?
- Chart.js line split color
- Custom scatter chart extended from scatter chart becomes line chart
- Fully destroy charts on ngDestroy method from Angular 4
- how to put yAxisLabel in chartjs
- Multiple ChartJS scripts are not working at the same time
- Chart.Js pie chart click
- Create multiple dynamic stacked chart using chart.js in Angular 10?
- Chart Js reduce text size for label on X axis
- Chart Click Event - Clicking label of doughnut chart, doesn't return label ng2-charts
- Hide or show two datasets with one click event of legend in chart.js
- Gantt Chart Timeline Chart js 3
- How to rewrite JavaScript currency formatting to abbreviate dollar amount
- How can i add a calculated value on top of the bars in Chart.js?
- Chart js footer
- Chartjs barchart group dataset by label
- I can't change the legend position in Laravel Charts & ChartJS
- How to make Chart JS responsive?
- Chart js 2.8 - How to make bars grow at the same speed?
- Chart.js is not respecting my container dimensions
- Chart js old chart data not clearing
- Can't resolve 'chart.js/auto'
- How to remove labels from ng2-chart(chart.js)
- Syntax Error: Token '{' invalid key at column 2 of the expression [{{id}}] starting at [{id}}]?
- How to add font color in vue-chartjs
- How to decrease bottom width of triangle using line chart in chartJs?
- Vue 2: How to unit test component that uses Chart.js (vue-chart-3)