ChartJS - 根据悬停数据显示百分比 (AngularJS)

ChartJS - Show percentage base on data on hover (AngularJS)

我在 angularjs 中有简单的 chartjs,悬停时会显示 (20%)。

HTML

JS

angular.module('chartDemo', ['chart.js']) .config(['ChartJsProvider', 函数 (ChartJsProvider) { // 配置所有图表 ChartJsProvider.setOptions({ //动画:假的, //响应:假 }); }]) .controller('MainController', MainController);

function MainController($scope, $timeout) { var vm = 这个;

vm.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
vm.data = [30, 50, 20];
vm.options = {
  legend: {
    display: true,
    position: 'bottom'
  },
  tooltips: {
    callbacks: {
      label: (ttItem,data) => (`${data.labels[ttItem.index]}: ${data.datasets[ttItem.datasetIndex].data[ttItem.index]}%`)
    }
  },
  cutoutPercentage: 60,
  tooltipEvents: [],
  tooltipCaretSize: 0,
  showTooltips: true,
  onAnimationComplete: function() {
    self.showTooltip(self.segments, true);
  }
}

}

MainController.$inject = ['$scope', '$timeout'];

Fiddle

https://jsfiddle.net/bheng/hegma4zn/2/

现在,它显示 % 正确,当数据种类匹配到 100% 像这样 [30, 50, 20]

如果数据看起来像这样 [360, 507, 207, 900] 那么代码将不再有效。

我有什么建议可以让它正常工作吗?


百分比

var percent = total/data.datasets[item.datasetIndex].data[item.index];

就是不知道总值怎么抢

首先获取total的数据我们可以使用Javascript的reduce方法

const total = vm.data.reduce((a, b) => a+b, 0);

现在更新标签回调以计算百分比。

        callbacks: {
        label: (ttItem,data) => (`${data.labels[ttItem.index]}: ${Math.round(data.datasets[ttItem.datasetIndex].data[ttItem.index]/total*10000)/100}%`)
      }

请注意,在上面的代码中,我将百分比四舍五入以显示 2 个小数点,您可能需要更改它。

这是 MainController 的完整代码。

function MainController($scope, $timeout) {
  var vm = this;
  
  vm.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales", "Other Sales"];
  
  vm.data = [360, 507, 207, 900];
  
  const total = vm.data.reduce((a, b)=> a+b, 0);
  
  vm.options = {
    legend: {
      display: true,
      position: 'bottom'
    },
    tooltips: {
        callbacks: {
        label: (ttItem,data) => (`${data.labels[ttItem.index]}: ${Math.round(data.datasets[ttItem.datasetIndex].data[ttItem.index]/total*10000)/100}%`)
      }
    },
    cutoutPercentage: 60,
    tooltipEvents: [],
    tooltipCaretSize: 0,
    showTooltips: true,
    onAnimationComplete: function() {
      self.showTooltip(self.segments, true);
    }
  }
  
}