Search code examples
chart.jsonhover

Display character after y-axis data value in onhover pop up Chart.js


I'm new to Chart.js and I'm having a little bit of trouble customizing the onHover() pop up. I want to add a percent symbol after the y axis data value on the pop up, so what would be displayed will look something like this, label: value%. I have tried using scaleLabel and ticks with now luck.

Right now this is how it looks:

enter image description here

and here is my code:

let chart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: dates, 
      datasets: [
        {
            label: 'Casos confirmados',
            backgroundColor: 'rgb(224, 224, 224)',
            borderColor: 'rgb(0, 0, 0)',
            data: confirmedCases
        }
      ]
    },
    options: {
        scales: {
            yAxes: [{
              gridLines: {
                drawTicks: true,
               },
                ticks: {

                  display : true,
                    // Include a percent sign in the ticks
                    callback: function(value, index, values) {
                        return value + '%';
                    }
                },
                scaleLabel: {
                    display: true,
                    labelString: '%'
                }
            }]
        }
    }
  });

If anyone could give me any pointers I would greatly appreciate it.


Solution

  • You can define tooltips.callbacks.label function inside the chart options as follows:

    tooltips: {
      callbacks: {
        label: (tooltipItem, data) => data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel + '%'
      }
    },
    

    Please take a look at your amended code and see how it works.

    let chart = new Chart('myChart', {
      type: 'line',
      data: {
        labels: ['A', 'B', 'C', 'D', 'E', ],
        datasets: [{
          label: 'Casos confirmados',
          backgroundColor: 'rgb(224, 224, 224)',
          borderColor: 'rgb(0, 0, 0)',
          data: [5, 6, 4, 3, 6]
        }]
      },
      options: {
        tooltips: {
          callbacks: {
            label: (tooltipItem, data) => data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel + '%'
          }
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true,
              callback: value => value + '%'
            },
            scaleLabel: {
              display: true,
              labelString: '%'
            }
          }]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <canvas id="myChart" height="90"></canvas>