Javascript Chart.js 2.0 甜甜圈工具提示百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37257034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:06:05  来源:igfitidea点击:

Chart.js 2.0 doughnut tooltip percentages

javascriptchart.jschart.js2

提问by wrennjb

I have worked with chart.js 1.0 and had my doughnut chart tooltips displaying percentages based on data divided by dataset, but I'm unable to replicate this with chart 2.0.

我使用过 chart.js 1.0 并且我的甜甜圈图工具提示显示了基于数据除以数据集的百分比,但我无法用图表 2.0 复制它。

I have searched high and low and have not found a working solution. I know that it will go under options but everything I've tried has made the pie dysfunctional at best.

我搜索了高低,并没有找到一个可行的解决方案。我知道它会在选项下进行,但我所尝试的一切充其量只能使馅饼功能失调。

<html>

<head>
    <title>Doughnut Chart</title>
    <script src="../dist/Chart.bundle.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <style>
    canvas {
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    }
    </style>
</head>

<body>
    <div id="canvas-holder" style="width:75%">
        <canvas id="chart-area" />
    </div>
    <script>
    var randomScalingFactor = function() {
        return Math.round(Math.random() * 100);
    };
    var randomColorFactor = function() {
        return Math.round(Math.random() * 255);
    };
    var randomColor = function(opacity) {
        return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
    };

    var config = {
        type: 'doughnut',
        data: {
            datasets: [{
                data: [
                    486.5,
                    501.5,
                    139.3,
                    162,
                    263.7,
                ],
                backgroundColor: [
                    "#F7464A",
                    "#46BFBD",
                    "#FDB45C",
                    "#949FB1",
                    "#4D5360",
                ],
                label: 'Expenditures'
            }],
            labels: [
                "Hospitals: 6.5 billion",
                "Physicians & Professional Services: 1.5 billion",
                "Long Term Care: 9.3 billion",
                "Prescription Drugs: 2 billion",
                "Other Expenditures: 3.7 billion"
            ]
        },
        options: {
            responsive: true,
            legend: {
                position: 'bottom',
            },
            title: {
                display: false,
                text: 'Chart.js Doughnut Chart'
            },
            animation: {
                animateScale: true,
                animateRotate: true
            }

        }
    };

    window.onload = function() {
        var ctx = document.getElementById("chart-area").getContext("2d");
        window.myDoughnut = new Chart(ctx, config);{

        }
    };


    </script>
</body>

</html>

回答by Quince

Update:The below answer shows a percentage based on total data but @William Surya Permanahas an excellent answer that updates based on the shown data https://stackoverflow.com/a/49717859/2737978

更新:下面的答案显示了基于总数据的百分比,但@William Surya Permana有一个很好的答案,根据显示的数据进行更新https://stackoverflow.com/a/49717859/2737978



In optionsyou can pass in a tooltipsobject (more can be read at the chartjs docs)

options您可以在传递tooltips对象(更可以在读取chartjs文档

A field of tooltips, to get the result you want, is a callbacksobject with a labelfield. labelwill be a function that takes in the tooltip item which you have hovered over and the data which makes up your graph. Just return a string, that you want to go in the tooltip, from this function.

的字段tooltips,为了得到你想要的结果,是一个callbacks带有label字段的对象。label将是一个函数,它接收您悬停在上面的工具提示项和构成图形的数据。只需从这个函数返回一个你想要进入工具提示的字符串。

Here is an example of what this can look like

这是一个例子

tooltips: {
  callbacks: {
    label: function(tooltipItem, data) {
      //get the concerned dataset
      var dataset = data.datasets[tooltipItem.datasetIndex];
      //calculate the total of this data set
      var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
        return previousValue + currentValue;
      });
      //get the current items value
      var currentValue = dataset.data[tooltipItem.index];
      //calculate the precentage based on the total and current item, also this does a rough rounding to give a whole number
      var percentage = Math.floor(((currentValue/total) * 100)+0.5);

      return percentage + "%";
    }
  }
} 

and a full example with the data you provided

以及您提供的数据的完整示例

fiddle

小提琴

var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
  return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
  return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};

var config = {
  type: 'doughnut',
  data: {
    datasets: [{
      data: [
        486.5,
        501.5,
        139.3,
        162,
        263.7,
      ],
      backgroundColor: [
        "#F7464A",
        "#46BFBD",
        "#FDB45C",
        "#949FB1",
        "#4D5360",
      ],
      label: 'Expenditures'
    }],
    labels: [
      "Hospitals: 6.5 billion",
      "Physicians & Professional Services: 1.5 billion",
      "Long Term Care: 9.3 billion",
      "Prescription Drugs: 2 billion",
      "Other Expenditures: 3.7 billion"
    ]
  },
  options: {
    responsive: true,
    legend: {
      position: 'bottom',
    },
    title: {
      display: false,
      text: 'Chart.js Doughnut Chart'
    },
    animation: {
      animateScale: true,
      animateRotate: true
    },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
         var dataset = data.datasets[tooltipItem.datasetIndex];
          var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
            return previousValue + currentValue;
          });
          var currentValue = dataset.data[tooltipItem.index];
          var percentage = Math.floor(((currentValue/total) * 100)+0.5);         
          return percentage + "%";
        }
      }
    }
  }
};


var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx, config); {

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="canvas-holder" style="width:75%">
  <canvas id="chart-area" />
</div>

回答by William Surya Permana

For those who want to display dynamic percentages based on what currently displayed on the chart (not based on total data), you can try this code:

对于那些想要根据图表上当前显示的内容(而不是基于总数据)显示动态百分比的人,您可以尝试以下代码:

 tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        var dataset = data.datasets[tooltipItem.datasetIndex];
        var meta = dataset._meta[Object.keys(dataset._meta)[0]];
        var total = meta.total;
        var currentValue = dataset.data[tooltipItem.index];
        var percentage = parseFloat((currentValue/total*100).toFixed(1));
        return currentValue + ' (' + percentage + '%)';
      },
      title: function(tooltipItem, data) {
        return data.labels[tooltipItem[0].index];
      }
    }
  },

回答by Luisus

I came across this question because I needed to show percentage on stacked bar charts. The percentage I needed was per stacked columns. I accomplished this by modifying Willian Surya's answer like this:

我遇到了这个问题,因为我需要在堆积条形图上显示百分比。我需要的百分比是每个堆叠的列。我通过像这样修改 Willian Surya 的回答来实现这一点:

tooltips: {
  callbacks: {
    label: function(tooltipItem, data) {
      var index = tooltipItem.index;
      var currentValue = data.datasets[tooltipItem.datasetIndex].data[index];
      var total = 0;
      data.datasets.forEach(function(el){
        total = total + el.data[index];
      });
      var percentage = parseFloat((currentValue/total*100).toFixed(1));
      return currentValue + ' (' + percentage + '%)';
    },
    title: function(tooltipItem, data) {
      return data.datasets[tooltipItem[0].datasetIndex].label;
    }
  }
}

This is the final result:

这是最终结果:

ChartJS Percentage for stacked bar charts

ChartJS 堆积条形图的百分比