1👍
✅
Here is a basic solution without plugins
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<div style="width: 450px; height: 450px;"><canvas id="myChart" width="400" height="400"></canvas></div>
<script>
function square_data(chart){
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFA500";
ctx.rect(145, 70, 15, 15);
ctx.fill()
ctx.fillStyle = "#fff";
ctx.fillText(chart.dataset.data[chart.dataIndex], 147,82, 10);
ctx.stroke();
return c
}
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016','2017', '2018', '2019', '2020'],
datasets: [{
fill:false,
label: 'Cantidad Estudiantes',
data: [12,15,9,0,9,13,13,16,26,22,0,18,9,10,11,8,9,12],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 3
}]
},
options: {
plugins: {
datalabels: {
anchor: 'start',
align: '-45',
clamp: true,
color: "orange",
}
},
elements:{
"point":{"pointStyle":square_data},
},
legend: {
labels: {
fontColor: "#acb5bf",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
);
</script>
</body>
</html>
It’s just an use case, fiddle here
2👍
You can use the datalabels plugin for this (https://v2_0_0-rc_1–chartjs-plugin-datalabels.netlify.app/samples/charts/line.html)
Example:
Chart.register(ChartDataLabels);
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: 'red'
}]
},
options: {
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 25,
borderWidth: 3,
color: 'white',
font: {
weight: 'bold'
},
padding: 6,
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script>
</body>
Source:stackexchange.com