简体   繁体   中英

Displaying dataset labels in Chart.js line graph

I've managed to create a Chart.js line graph that contains multiple datasets. However, how can I modify the tooltip such that when I hover over a point, the label of the datasets is displayed as well as the £ symbol?

For example, from my screenshot, I'd like to display:

31/10/2015
(label) - £100.00
(label) - £240.00
(label) - £150.00

在此处输入图片说明

javascript code:

<script type="text/javascript">

gon.balances.reverse();
var balancesSortByAccId = gon.balancesSortByAccId;

var data = {
    labels: [],
    datasets: []
};

//loop through all accounts to generate datasets
for(var account in gon.balancesSortByAccId){
  var balances = [];
  var dates = [];

  var accountData = gon.balancesSortByAccId[account];

  for (var i in accountData) {
    balances.push(parseFloat(accountData[i].balance).toFixed(2)); 
    dates.push(convertDate(accountData[i].date));

    for (var date in dates)
      if (data.labels.indexOf(dates[date]) <= -1)
        data.labels.push(dates[date]);
  }

  var colour = getRandomColor();

  var chartjs_balances =           {
              label: account,
              fillColor: "rgba(220,220,220,0.2)",
              strokeColor: colour,
              pointColor: colour,
              pointStrokeColor: colour,
              pointHighlightFill: "#fff",
              pointHighlightStroke: "rgba(220,220,220,1)",
              data: balances
          };


  data.datasets.push(chartjs_balances);
}

var options = {
  responsive: true,
};

//draw graph
var ctx = document.getElementById("history_canvas").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, options);

//convert date to dd/mm/yyyy format
function convertDate(inputFormat) {
  function pad(s) { return (s < 10) ? '0' + s : s; }
  var d = new Date(inputFormat);
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}

//return random color for each dataset
function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

UPDATE:

I've managed to display the £ symbol with the following update:

var options = {
  responsive: true,
  multiTooltipTemplate: "<%%=label%>: £<%%= value %>"
};

However, the output of that is the following and not completely how I want it since it displays the date instead of the account label:

31/10/2015
31/10/2015 - £100.00
31/10/2015 - £240.00
31/10/2015 - £150.00

I managed to resolve this with the following:

var options = {
  responsive: true,
  multiTooltipTemplate: "<%%=datasetLabel%>: £<%%= value %>",
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM