最近,我致力于使用chart.js在图表中显示数据库表中的数据。在该图形工具提示中,有2个数据正在显示,但现在我也想在该工具提示中合并第3个数据。

喜欢:

2016年1月的客户

2016年的每月contomers:-4.5

损失15%(第三名)

以下是当前图表的快照
jquery - 如何在chart.js中的图形工具提示中附加更多数据-LMLPHP

这也是db表数据的屏幕截图

jquery - 如何在chart.js中的图形工具提示中附加更多数据-LMLPHP

这是我的代码

    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var data = JSON.parse(data);
            var month = [];
            var customers = [];

            for(var i in data) {
                month.push("Customer in " + data[i].apply_month);
                customers.push(data[i].no_customers);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers for Year 2016',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers,
                        fill: false
                    }

                ]
            };

            // alert(chartdata);

            var frame = $("#mycanvas");

            var barGraph = new Chart(frame, {
                type: 'line',
                data: chartdata
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});


现在请提出建议,我该如何在这些工具提示中附加第三数据。谢谢 :)

最佳答案

您可以使用工具提示的afterBody回调函数来实现此目的...

options: {
   tooltips: {
      callbacks: {
         afterBody: function(t, d) {
            return 'loss 15%';  // return a string that you wish to append
         }
      }
   },
   ...
}


这是一个有效的例子...



var ctx = document.getElementById("myChart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
      datasets: [{
         label: 'Standard Rating',
         data: [1, 2, 3, 4, 5, 6],
         backgroundColor: 'rgba(209, 230, 245, 0.5)',
         borderColor: 'rgba(56, 163, 236, 1)',
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      tooltips: {
         callbacks: {
            afterBody: function(t, d) {
               return 'loss 15%'; //return a string that you wish to append
            }
         }
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>

09-30 16:42
查看更多