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

时间:2017-06-08 05:37:28

标签: jquery graph chart.js

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

像:

2016年Jaunary的客户

2016年月度调查对象:-4.5

损失15%(第3名)

以下是当前图表的快照 enter image description here

这里还有一个db表数据截图

enter image description here

这是我的代码

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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

&#13;
&#13;
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
            }
         }]
      }
   }
});
&#13;
<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>
&#13;
&#13;
&#13;