How to display Line Chart dataset point labels with Chart.js?

后端 未结 4 2138
梦如初夏
梦如初夏 2020-12-31 20:59

I have a design requirement to display a line chart with 5 datasets of trends data. Each data value along the stroke lines need to be showing a data value label at its respe

4条回答
  •  不思量自难忘°
    2020-12-31 21:22

    Here's how to do it based on the example provided on github. It looks similar to your solution...

    // Define a plugin to provide data labels
    Chart.plugins.register({
        afterDatasetsDraw: function(chart, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chart.ctx;
            chart.data.datasets.forEach(function (dataset, i) {
                var meta = chart.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';
                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();
                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';
                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });
    

    From Code: https://github.com/chartjs/Chart.js/blob/master/samples/advanced/data-labelling.html

    Example: http://www.chartjs.org/samples/latest/advanced/data-labelling.html

    You can also define plugins inline to the chart instead of globally...

    var chart = new Chart(ctx, {
        plugins: [{
            afterDatasetsDraw: ...
        }]
    });
    

提交回复
热议问题