Skip to content Skip to sidebar Skip to footer

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.d

Solution 1:

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

Post a Comment for "How Can I Display The Percentage Inside The Graph And On Hover?"