Search code examples
javascriptangularchart.jsaxis-labels

Update chart axis labels after hover - chart.js


I'm working with chart.js version 3.7.1. I want to replace y axis labels after hovering it. Hover event works fine and it recognizes y axis quite good but labels don't replace. I tried using update() method from Chart API but it didn't help.

I also prepared some quick playground where I placed a custom chart with this problem. https://stackblitz.com/edit/angular-ivy-x3sncg


Solution

  • You could combine your afterEvent plugin with a ticks.callback function as shown below:

    options: {
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: value => value + (this.isHoveringYAxe ? '$' : '')
          }
        }
      }
    },
    plugins: [{
      id: 'customHover',
      afterEvent: (chart, args) => {
        const event = args.event;
        if (event.type == 'mousemove') {
          if (event.x < chart.scales.y.width && !this.isHoveringYAxe) {
            this.isHoveringYAxe = true;
            chart.update();
          } else if (event.x >= chart.scales.y.width && this.isHoveringYAxe) {
            this.isHoveringYAxe = false;
            chart.update();
          }
        }
      }
    ]
    

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