Chart.js 2.0 donut工具提示百分比

时间:2016-05-16 15:01:08

标签: javascript chart.js chart.js2

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

我搜索过高和低,并没有找到可行的解决方案。我知道它会受到选择,但我所尝试的一切都让馅饼功能失调。

<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: $486.5 billion",
                "Physicians & Professional Services: $501.5 billion",
                "Long Term Care: $139.3 billion",
                "Prescription Drugs: $162 billion",
                "Other Expenditures: $263.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>

4 个答案:

答案 0 :(得分:80)

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

options中,您可以传入tooltips个对象(可以在chartjs docs阅读更多内容)

要获得所需结果的tooltips字段是callbacks字段,其中包含label字段。 label将是一个函数,它接收您悬停的工具提示项和构成图表的数据。只需从此函数返回一个您想要进入工具提示的字符串。

这是一个看起来像什么的例子

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 + "%";
    }
  }
} 

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

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: $486.5 billion",
      "Physicians & Professional Services: $501.5 billion",
      "Long Term Care: $139.3 billion",
      "Prescription Drugs: $162 billion",
      "Other Expenditures: $263.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>

答案 1 :(得分:29)

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

function createUser(){

    var values = [];
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "/Some/Path", false);
    xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhttp.setRequestHeader("Accept", "text/html");

    xhttp.send('a=a');
}

答案 2 :(得分:0)

我遇到了这个问题,因为我需要在堆积的条形图上显示百分比。我需要的百分比是每堆叠列。我是通过修改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;
    }
  }
}

这是最终结果:

ChartJS Percentage for stacked bar charts

答案 3 :(得分:0)

用法在3.x及更高版本中发生了变化,所以我会附上一个方法。

const data: ChartData = {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
        {
            data: excerciseData,
            backgroundColor: [
                "rgba(255, 99, 132, 0.5)",
                "rgba(54, 162, 235, 0.5)",
                "rgba(255, 206, 86, 0.5)",
                "rgba(75, 192, 192, 0.5)",
                "rgba(153, 102, 255, 0.5)",
                "rgba(255, 159, 64, 0.5)"
            ]
        }
    ]
};
...

     callbacks: {
                    label: tooltipItem => {
                        let total = 0;
                        data.datasets[0].data.forEach(num => {
                            total += num as number;
                        });
                        const currentValue = data.datasets[0].data[tooltipItem.dataIndex] as number;

                        const percentage = ((currentValue * 100) / total).toFixed(1) + "%";

                        return `${currentValue}(${percentage})`;
                    },
                    title: tooltipItems => {
                        return tooltipItems[0].label;
                    }
                }