如何在条形图(chart.js)上显示数据值?

时间:2017-11-22 06:50:27

标签: php chart.js

我想在条形图的顶部显示值,但我无法做到。有没有办法让我展示价值观?我试图寻找已解决的同样问题,但没有任何作用。

这是我目前的代码:

app.js

$(document).ready(function() {
$.ajax({
  url: "http://172.16.13.35:8080/MonthlyMonitoring/data2.php",
  method: "GET",
  success: function(data2) {
     console.log(data2);
     var monthly = [];
     var kwh = [];

     for (var i in data2) {
        monthly.push(data2[i].monthly);
        kwh.push(data2[i].kwh);
     }

     var chartdata = {
        labels: monthly,
        datasets: [{
           label: 'KWH Monthly',
           backgroundColor: 'rgb(255, 158, 1)',
           borderColor: 'rgba(134,159,152, 1)',
           hoverBackgroundColor: 'rgba(223, 178, 82, 0.71)',
           hoverBorderColor: 'rgba(230, 236, 235, 0.75)',
           data: kwh
        }]
     };

     var ctx = $("#mycanvas2");

     var barGraph = new Chart(ctx, {
        type: 'bar',
        data: chartdata,
        showTooltips: false,
        options: {
           scales: {
              yAxes: [{
                 ticks: {
                    beginAtZero: true
                 }
              }]
           }
        }
     });


   },

  error: function(data2) {
     console.log(data2);
  }
 });
});

的index.php

<div id="chart-container1">
     <canvas id="mycanvas2"></canvas> 
</div>

1 个答案:

答案 0 :(得分:0)

尝试根据您的需要调整此示例中的 data labelling plugin

See in action

// 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.chart.ctx; // DIFFERS FROM ORIG VERSION

        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);
                });
            }
        });
    }
});