Reputation: 1
I'm making a bar chart using Chartjs in my AngularJS application. I'm able to render the chart, however, I'm not able to find a way to show the value of each bar on top of it. The solutions I found were for Angular apps and not for AngularJs apps.
Here is my canvas tag :
My JS file code:
$scope.labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July'];
$scope.data = [[75, 63, 59, 79, 13, 91, 113]];
$scope.ColorBar = ['#90EE90', '#FF6600'];
$scope.DataSetOverride = [{ yAxisID: 'y-axis-1' }];
$scope.options = {
legend: { display: true },
responsive: true,
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
}]
}
}
Upvotes: 0
Views: 1337
Reputation: 31331
If you dont want to use the datalabels plugin you can write your own basic version of it as an inline plugin like so:
const customDatalabalesPlugin = {
id: 'customDatalabels',
afterDatasetsDraw: (chart, args, opts) => {
const {
ctx,
_metasets
} = chart;
const lineHeight = ctx.measureText('M').width;
const color = opts.color || 'black';
for (let i = 0; i < chart.data.datasets.length; i++) {
const meta = chart.getDatasetMeta(i)
meta.data.forEach((el) => {
//console.log(el)
const dpVal = el._chart.data.datasets[el._datasetIndex].data[el._index];
const text = dpVal.toString();
const textWidth = ctx.measureText(text).width;
ctx.fillStyle = color;
ctx.fillText(text, (el._model.x - textWidth / 2), (el._model.y - lineHeight));
});
}
}
}
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12.4, 19.234, 3.23213, 5.4, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
customDatalabels: {
color: 'green', // Color each character individual collor
// color: 'pink' // Color whole label this collor
}
}
},
plugins: [customDatalabalesPlugin]
}
const 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/2.9.4/Chart.js"></script>
</body>
About using private variables in the plugin, it can be done savely since there wont be another release of version 2 for chart.js so they wont get changed anymore.
Upvotes: 1
Reputation: 1788
For this type of feature you should use the chartjs-plugin-datalabels which does exactly this.
Something like this should solve your problem:
options: {
plugins: {
datalabels: {
color: 'blue',
labels: {
value: {
color: 'green'
}
}
}
}
}
The documentation is quite good. You should find everything you need there.
Upvotes: 1