如何在图表内和悬停时显示百分比?

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

到目前为止,我还不知道如何在图表中显示百分比符号。

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

这是为了悬停,但它不起作用。未显示百分比符号。

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

这也在codesandbox中:https://codesandbox.io/s/bar-graph-9nr8u?file=/src/App.js:3205-3719

您可以像这样使用格式化函数添加百分比:

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}%`
    }
  }
}

如果您希望显示百分比本身而不是百分号,则需要像这样计算它们:

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