在echars餅圖legend圖例中顯示佔比數
查資料發現echarts通過最大餘額算法計算佔比,記錄下方便使用
getPercentValue()
getPercentValue(valueList, idx, precision){// 傳入參數(數組數據,數組下標,精度)
// 判斷是否爲空
if (!valueList[idx]) {
return 0;
}
// 求和
var sum = valueList.reduce(function (acc, val) {
return acc + (isNaN(val) ? 0 : val);
}, 0)
if (sum === 0) {
return 0;
}
// 10的2次冪是100,用於計算精度。
var digits = Math.pow(10, precision);
// 擴大比例100,
var votesPerQuota = valueList.map(function (val) {
return (isNaN(val) ? 0 : val) / sum * digits * 100;
})
// 總數,擴大比例意味的總數要擴大
var targetSeats = digits * 100;
// 再向下取值,組成數組
var seats = votesPerQuota.map(function (votes) {
return Math.floor(votes);
})
// 再新計算合計,用於判斷與總數量是否相同,相同則佔比會100%
var currentSum = seats.reduce(function (acc, val) {
return acc + val;
}, 0)
// 餘數部分的數組:原先數組減去向下取值的數組,得到餘數部分的數組
var remainder = votesPerQuota.map(function (votes, idx) {
return votes - seats[idx];
})
// 給最大最大的餘額加1,湊個佔比100%;
while (currentSum < targetSeats) {
// 找到下一個最大的餘額,給其加1
var max = Number.NEGATIVE_INFINITY;
var maxId = null;
for (var i = 0, len = remainder.length; i < len; ++i) {
if (remainder[i] > max) {
max = remainder[i];
maxId = i;
}
}
// 對最大項餘額加1
++seats[maxId];
// 已經增加最大餘數加1,則下次判斷就可以不需要再判斷這個餘額數。
remainder[maxId] = 0;
// 總的也要加1,爲了判斷是否總數是否相同,跳出循環。
++currentSum;
}
// 這時候的seats就會總數佔比會100%
return seats[idx] / digits
},
legend.tooltip.formatter
formatter: function (tool) {
let numArr=[]
let numIndex=0
let indexNum=0
seriesArr.forEach((item,index) => {
numArr.push(item.value)
if(tool.name === item.name){
numIndex =index
indexNum = item.value
}
})
if(indexNum === 0){
return `類型佔比</br>${tool.name}:${indexNum} (0%)`
}else{
return `類型佔比</br>${tool.name}:${indexNum} (${_selfThis.getPercentValue(numArr,numIndex,2)}%)`
}
},