Chartjs Place Y-axis Labels Between Ticks
I have the following graph: However, i'd like to shift the y axis labels to be the following: Is it possible to move the y axis labels in between the tick marks with ChartJS, like
Solution 1:
Unfortunately, there is no built-in method in ChartJS for this, at the moment.
You would rather need to create a chart plugin to achieve that.
plugins: [{
beforeDraw: function(chart) {
var ctx = chart.ctx;
var yAxis = chart.scales['y-axis-0'];
var tickGap = yAxis.getPixelForTick(1) - yAxis.getPixelForTick(0);
yAxis.options.ticks.fontColor = 'transparent'; // hide original tick// loop through ticks arrayChart.helpers.each(yAxis.ticks, function(tick, index) {
if (index === yAxis.ticks.length - 1) return;
var xPos = yAxis.right;
var yPos = yAxis.getPixelForTick(index);
var xPadding = 10;
// draw tick
ctx.save();
ctx.textBaseline = 'middle';
ctx.textAlign = 'right';
ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
ctx.restore();
});
}
}]
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var barChart = newChart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
label: 'BAR',
data: [10, 20, 30],
backgroundColor: 'rgba(0, 119, 204, 0.5)'
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
plugins: [{
beforeDraw: function(chart) {
var ctx = chart.ctx;
var yAxis = chart.scales['y-axis-0'];
var tickGap = yAxis.getPixelForTick(1) - yAxis.getPixelForTick(0);
yAxis.options.ticks.fontColor = 'transparent'; // hide original tick// loop through ticks arrayChart.helpers.each(yAxis.ticks, function(tick, index) {
if (index === yAxis.ticks.length - 1) return;
var xPos = yAxis.right;
var yPos = yAxis.getPixelForTick(index);
var xPadding = 10;
// draw tick
ctx.save();
ctx.textBaseline = 'middle';
ctx.textAlign = 'right';
ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
ctx.restore();
});
}
}]
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script><canvasid="ctx"height="200"></canvas>
Solution 2:
I think you can use: yAxes: [{gridLines: { offsetGridLines: true }}]
to do this. The label value will be the avg between the thicks.
Post a Comment for "Chartjs Place Y-axis Labels Between Ticks"