【问题标题】:How can I display the percentage inside the graph and on hover?如何在图表内和悬停时显示百分比?
【发布时间】:2021-09-28 12:04:41
【问题描述】:

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

  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

【问题讨论】:

    标签: javascript reactjs chart.js react-chartjs react-chartjs-2


    【解决方案1】:

    您可以像这样使用格式化程序功能添加百分比:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-27
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      相关资源
      最近更新 更多