3👍
If you are using the DataLabels plugin, here is how you can do a scriptable display option.
In the plugin options you can use a function to dictate whether DataLabels shows a label. So in this case its a simple check if the value is greater than 0.
var ctx = document.getElementById("myChart");
debugger;
var data = {
labels: ["Jan 18", "Feb 18", "Mar18", "Apr 18", "May 18", "Jun 18", "Jul 18"],
datasets: [{
label: "# of Votes",
data: [0, 0, 0, 0, 10, 12, 24]
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
legend: {
"display": false
},
plugins: [ChartDataLabels],
options: {
plugins: {
// Change options for ALL labels of THIS CHART
datalabels: {
color: "#36A2EB",
anchor: "end",
display: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value > 0; // display labels with a value greater than 0
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.5.0/dist/chartjs-plugin-datalabels.min.js"></script>
<canvas id="myChart" width="100" height="100"></canvas>
1👍
How about formatting text shown on animation.onComplete?
var ctx = document.getElementById("myChart");
debugger;
var data = {
labels: ["2 May", "9 May", "16 May", "23 May", "30 May", "6 Jun", "13 Jun"],
datasets: [{
data: [0, 0, 56, 50, 88, 60, 45],
backgroundColor: "#EEEEEE"
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
legend: {
"display": false
},
options: {
"hover": {
"animationDuration": 0
},
"animation": {
"duration": 1,
"onComplete": function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
if (data) {
ctx.fillText(data, bar._model.x, bar._model.y - 5);
}
});
});
}
}
}
});
<!doctype html>
<html>
<head>
<title>example.com/test</title>
</head>
<body>
<canvas id="myChart" width="100" height="100"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
</body>
</html>
0👍
I added just a condition in the plugin’s render and it worked perfectly.
plugins: {
labels: {
render: function (args) {
if (args.value != 0)
return args.value;
},
fontSize: 10
}
},
Source:stackexchange.com