3👍
You can change the xAxes
label positions with the following steps:
-
Add
.getContext("2d")
to the call that gets thectx
canvas object:var ctx = document.getElementById("gescanntePackzettelChart").getContext("2d");
-
Hide the current xAxes
ticks
:xAxes: [{ ticks: { display: false } }
-
Add an
animation
to theoptions
config, and use the canvasfillText()
method to create new labels:animation: { duration: 1, onComplete: function() { var controller = this.chart.controller; var chart = controller.chart; var xAxis = controller.scales['x-axis-0']; var numTicks = xAxis.ticks.length; var xOffsetStart = xAxis.width / numTicks; var halfBarWidth = (xAxis.width / (numTicks * 2)); xAxis.ticks.forEach(function(value, index) { var xOffset = (xOffsetStart * index) + halfBarWidth; var yOffset = chart.height - 20; ctx.fillText(value, xOffset, yOffset); }); } }
For
xOffset
, to figure out the correct position, take thexAxis
width and divide it by the number of tick labels. This will tell you how wide each bar is. Then, multiply that number by the currentindex
to position the label in front of the correct bar. Finally, add add the width of half a bar to center the labels in the bar.For the
yOffset
, start with the chart’s height and subtract however much you want to move the labels up.
Working JSFiddle: https://jsfiddle.net/m5tnkr4n/124
- [Chartjs]-Chartjs backgroundColor for line chart does not appear in Vue app
- [Chartjs]-ChartJS not rendering lines according to x-axis data
0👍
Building on @Tot-Zam’s response, it’s possible to use the ChartJs scale object’s methods to define the context pixel coordinates easier. You also don’t need to define a ctx
object – it is already accessible using the this.chart
object.
animation: {
duration: 0,
onComplete: function() {
let chart = this.chart;
let controller = chart.controller;
let axis = controller.scales['x-axis-0'];
let yOffset = chart.height - 5;
axis.ticks.forEach(function(value, index) {
let xOffset = axis.getPixelForValue(value);
chart.ctx.fillText(value, xOffset, yOffset);
})
}
}
Working repl: https://repl.it/@lunarplasma/ChartJs-custom-axis-labels
- [Chartjs]-How to change X-Axis Interval on Chart.js
- [Chartjs]-Create an interactive custom tooltip for chartjs