How to add index labels(on top of bar charts) in C

2019-06-05 06:31发布

问题:

I am using angular-chart.js(which uses Chart.js) to create charts in my angular app. I want to add values on top of the bars in a bar chart. If extending the defaults charts in Chart.js is the only way, can you please provide a reference code?

回答1:

You can use the answer here how to display data values on Chart.js and modify the callback function slightly to show the index values instead of the values

...
this.datasets.forEach(function (dataset) {
    dataset.bars.forEach(function (bar, i) {
        ctx.fillText(i + 1, bar.x, bar.y - 5);
    });
})
...

The callback can be passed in via the angular-chart options parameter. You won't be extending the chart type, so you won't need to register a new directive with angular-chart.


Fiddle - http://jsfiddle.net/zkqu7tsp/



回答2:

This is the onAnimationComplete callback for angular-chart options

onAnimationComplete: function () {
        var chart = this.chart;
        var ctx = this.chart.ctx;
                                                                     this.datasets.forEach(function (dataset) {
         dataset.bars.forEach(function (bar, i) {
         console.log(bar)
             ctx.fillText(bar.value, bar.x, bar.y - 5);
         });
     })

Hope this helps you ..