簡體   English   中英

ChartJS - 根據 hover (AngularJS) 上的數據顯示百分比

[英]ChartJS - Show percentage base on data on hover (AngularJS)

我在 angularjs 中有簡單的 chartjs,懸停時會顯示 (20%)。

在此處輸入圖像描述

HTML

JS

angular.module('chartDemo', ['chart.js']).config(['ChartJsProvider', function (ChartJsProvider) { // 配置所有圖表 ChartJsProvider.setOptions({ //animation: false, //responsive: false }); }]).controller('MainController', MainController);

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

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'];

小提琴

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);

現在更新 label 回調來計算百分比。

        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);
    }
  }
  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM