Search code examples
javascriptchart.jstooltipstacked-chart

Chart.js/Ng-charts stacked bar chart - display percentages on bar, but actual values on tooltip


I have the following code which loops through an array of keys and plot the group 1 and group 2 scores on each one.

I want the stacked bar chart to show the percentages (each group has a different number of people to work the percentage out from), so i have worked out the percentages and pushed them into the data array.

For the tooltip, I want it to show the actual value (not the percentage), so I have made an actualValue array for the tooltip.

        for (let key of this.keys) {
            subject.stackedChartData.push({
                data: [
                  ((subject[key.label + "Group 1"] / this.totalNumberOfGroup1) * 100).toFixed(0),
                  ((subject[key.label + "Group 2"] / this.totalNumberOfGroup2) * 100).toFixed(0),
                ],
                label: key.label,
                actualValue: [subject[key.label + "Group 1"], subject[key.label + "Group 2"]],
              });
          }

My question is, how can i get the tooltip to display the actual value instead of the data percentage value.

I tried adding this to my stackedChartOptions, which does show the actualValue, but all of them in a long list for group 1 and 2, rather than just the one i'm hovering over

 tooltips: {
      mode: "label",
      callbacks: {
        label: (tooltipItem, data) => {
          return data.datasets[tooltipItem.datasetIndex].actualValue;
        },
      },
    },

Solution

  • You target the array as one object to return, if you only want to return the individual value you also need to target that like so:

    label: (tooltipItem, data) => {
      return data.datasets[tooltipItem.datasetIndex].actualValue[tooltipItem.dataIndex];
    },