Search code examples
javascriptreactjschart.jsreact-chartjsreact-chartjs-2

How can I display the percentage inside the graph and on hover?


So far, I do not yet know how to display the percentage symbol inside the graph.

  plugins: {
    datalabels: {
      backgroundColor: function (context) {
        return context.dataset.backgroundColor;
      },
      borderRadius: 25,
      borderWidth: 3,
      color: "black",
      font: {
        weight: "bold"
      },
      padding: 6
    },

This is for the hover but it's not working. No percentage symbol is displaying.

    tooltip: {
      callbacks: {
        label: (ttItem) => ttItem.label
      }
    }
  }

This is also in codesandbox:https://codesandbox.io/s/bar-graph-9nr8u?file=/src/App.js:3205-3719


Solution

  • You can add the percentage with the formatter function like so:

    plugins: {
      datalabels: {
        backgroundColor: function(context) {
          return context.dataset.backgroundColor;
        },
        formatter: (val, context) => `${val}%`,
        borderRadius: 25,
        borderWidth: 3,
        color: "black",
        font: {
          weight: "bold"
        },
        padding: 6
      },
    
      tooltip: {
        callbacks: {
          label: (ttItem) => `${ttItem.label}: ${ttItem.parsed}%`
        }
      }
    }
    

    If instead of only a percentage sign you want the percentages itself to be displayed you will need to calculate them like so:

    plugins: {
      datalabels: {
        backgroundColor: function(context) {
          return context.dataset.backgroundColor;
        },
        formatter: (val, context) =>
          `${
                      (Number(val) * 100) /
                      context.chart.data.datasets[context.datasetIndex].data.reduce(
                        (a, b) => Number(a) + Number(b),
                        0
                      )
                    }%`,
        //formatter: (val, context) => `${val}%`,
        borderRadius: 25,
        borderWidth: 3,
        color: "black",
        font: {
          weight: "bold"
        },
        padding: 6
      },
    
      tooltip: {
        callbacks: {
          label: (ttItem) =>
            `${ttItem.label}: ${
                        (ttItem.parsed * 100) /
                        ttItem.dataset.data.reduce(
                          (a, b) => Number(a) + Number(b),
                          0
                        )
                      }%`
          //label: (ttItem) => `${ttItem.label}: ${ttItem.parsed}%`
        }
      }
    }
    

    https://codesandbox.io/s/bar-graph-forked-43wzq?file=/src/App.js:3215-3797