I want to display different strings on the tooltip Title of the two line graphs.

Asked 2 years ago, Updated 2 years ago, 85 views

The two line graphs show this year's sales and last year's sales.

$xlabelThis='20/03', '20/04', '20/05', '20/06';
$xlabelLast='19/03', '19/04', '19/05', '19/06';

One line graph uses $xlabelThis declared in PHP as the title of the tooltip, but the other line graph should reflect the contents of $xlabelLast.
I would appreciate it if you could let me know.

varctx= document.getElementById("uriageChart");
var myLineChart = new Chart(ctx,{
type: 'line',

    data: {
      labels:[{$xlabelThis}],

      datasets:
        {
          label: 'This year (million yen),
          lineTension: 0,
          data: [3000, 7000, 4000, 3000],
          borderColor: "rgba(255,0,0,1)",
          backgroundColor: "rgba(0,0,0,0)"
        },
        {
          label: 'Last year (million yen),
          lineTension: 0,
          data: [1000, 3000, 5000, 2000],
          borderColor: "rgba(0,0,255,1)",
          backgroundColor: "rgba(0,0,0,0)"
        }
      ],
    },
    options: {
      tooltips:
          mode: 'nearest',
          intersect: false,
          callbacks: {
              title:function(tooltipItem,data){
                  return '';
              },
              label: function(tooltipItem,data){
                  return tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ', ')+'yen';
              }
          }
      },
      title: {
        display —true,
        text: 'Sales'
      },
      scale: {
        yAxes: [{
          ticks: {
            callback:function(value, index, values){
              return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ', ')+'yen';
            }
          }
        }]
      },
    }
  });

javascript chart.js

2022-09-29 22:37

1 Answers

Chart.js Tooltip Callback

or You can see it by looking at the sample page

You can rewrite the title in the tooltips callback.

The remodeled part is

var xlabelThis=['20/03', '20/04', '20/05', '20/06'];
var xlabelLast=['19/03', '19/04', '19/05', '19/06'];
variables = [xlabelThis, xlabelLast ];
tools: {
callbacks: {
 title:function(tooltipItem,data){
  variable=title [ tooltipItem[0].datasetIndex];
  return title [tooltipItem[0].index];
}

tooltipItem[0].datasetIndex is 0 or 1 as shown in and last year is switched.
tooltipItem[0].index tells you what element it is, so
All you have to do is return the title you want to see with a string.

Enter a description of the image here
Enter a description of the image here


2022-09-29 22:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.