How to add text at end of each line in charts.js
You can extend line controller drawing serie labels at the end of each line:
var chartData = {
datasets: [{
label: 'serie1',
backgroundColor: 'rgba(255, 255, 255, 0.0)',
borderColor: 'rgba(0, 119, 290, 0.6)',
data: [{x: 1, y: 10}, {x: 2, y: 12}, {x: 3, y: 18}, {x: 4, y: 5}, {x: 5, y: 25}, {x: 6, y: 30}]
},
{
label: 'serie2',
backgroundColor: 'rgba(255, 255, 255, 0.0)',
borderColor: 'rgba(120, 0, 190, 0.6)',
data: [{x: 1, y: 8}, {x: 2, y: 9}, {x: 3, y: 16}, {x: 4, y: 8}, {x: 5, y: 12}, {x: 6, y: 20}]
},
{
label: 'serie3',
backgroundColor: 'rgba(255, 255, 255, 0.0)',
borderColor: 'rgba(0, 200, 10, 0.6)',
data: [{x: 1, y: 10}, {x: 2, y: 5}, {x: 3, y: 26}, {x: 4, y: 18}, {x: 5, y: 19}, {x: 6, y: 10}]
}]
};
var originalController = Chart.controllers.line;
Chart.controllers.line = Chart.controllers.line.extend({
draw: function() {
originalController.prototype.draw.call(this, arguments);
drawLabels(this);
}
});
function drawLabels(t) {
ctx.save();
ctx.font = Chart.helpers.fontString(12, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = 'red';
ctx.textBaseline = 'bottom';
var chartInstance = t.chart;
var datasets = chartInstance.config.data.datasets;
datasets.forEach(function(ds, index) {
var label = ds.label;
var meta = chartInstance.controller.getDatasetMeta(index);
var len = meta.data.length-1;
//console.log(ds, meta.data[len]._model);
var xOffset = meta.data[len]._model.x+10;
var yOffset = meta.data[len]._model.y;
ctx.fillText(label, xOffset, yOffset);
});
ctx.restore();
}
var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
legend: { display: false },
scales: {
xAxes: [{
type: 'linear',
scaleLabel: { display: true, labelString: 'x' }
}],
yAxes: [{
ticks: { min: 0 },
scaleLabel: { display: true, labelString: 'y' }
}]
},
layout: {
padding: {
left: 0,
right: 60,
top: 20,
bottom: 0
}
}
}
});
#myChart {
border: solid 1px rgba(255, 0, 0, 0.5);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" height="300" width="500"></canvas>
Here is a jsfiddle: http://jsfiddle.net/beaver71/q62yv516/
plugins = [
{
id: 'customPlugin',
beforeDraw: chart => {
const datasets = chart.config.data.datasets;
if (datasets) {
const { ctx } = chart.chart;
ctx.save();
ctx.fillStyle = 'black';
ctx.font = '400 12px Open Sans, sans-serif';
for (let i = 0; i < datasets.length - 1; i++) {
const ds = datasets[i];
const label = ds.label;
const meta = chart.getDatasetMeta(i);
const len = meta.data.length - 1;
const xOffset = chart.canvas.width - 26;
const yOffset = meta.data[len]._model.y;
ctx.fillText(label, xOffset, yOffset);
}
ctx.restore();
}
}
}
];
Same as above, but as a plugin