1

I am using ChartJS v.2, and I would like to label arrayX by a string that will appear when the mouse will be on hover displaying the coordinates.

ArrayX being points (numbers) I should label with something.

 data = {
      labels: arrayX,
      datasets: [{
        label: 'ArrayY',
        data: arrayY,
        fill: false,
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
      }]
    };

enter image description here

OutOfMemoryError
  • 391
  • 2
  • 4
  • 16

2 Answers2

1

You can use the title callback for this:

var options = {
  type: 'line',
  data: {
    labels: ["10", "15", "30", "80", "5000", "999999"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    tooltips: {
      callbacks: {
        title: (a) => ('Test string: ' + a[0].label)
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • if I put semi-quote for the message it doesn't work for this part title: (a) => (`Test string: ${a[0].label}`) – OutOfMemoryError Oct 20 '21 at 21:16
  • but I have a classic way to start the code, is this: 'var myChart1 = new Chart('myChart', { type : 'line', etc etc ' can you please modify the start to accomplish this. – OutOfMemoryError Oct 20 '21 at 21:27
  • Thats because those are not semi-qoutes but instead are backticks for a string template, updated example with normal string semi-qoutes – LeeLenalee Oct 20 '21 at 23:02
0

I solved using this way, more easy.

options: {
            tooltips: {
              callbacks: {
                title:function(tooltipItems, data){
                     return 'Y: ' + tooltipItems[0].xLabel;
                } 
              }
            }
          }
OutOfMemoryError
  • 391
  • 2
  • 4
  • 16