ECharts 柱狀圖 -- 會隨著值的大小變化的漸變色
阿新 • • 發佈:2018-12-23
Echarts 柱狀圖
效果圖:
0 ~ 20: 綠色
20 ~ 200: 綠色 — 黃色 — 紅色
200 ~ : 紅色
var myCharts = echarts.init(document.getElementById("view"));
/* 基礎資料 */
var base = [220, 150, 189, 40, 90, 126, 280];
var warningValue = 20; //警告值
var errorValue = 220; //錯誤值
var normal = []; //正常範圍 0~20
var warning = []; //警告範圍 20~200
var error = []; //錯誤範圍 200~
/* 簡單的資料處理 */
base.forEach(function (value, index, data) {
normal[index] = data[index] > warningValue ? warningValue : data[index];
});
base.forEach(function (value, index, data) {
error[index] = data[index] < errorValue ? 0 : data[index] - errorValue;
});
base.forEach(function (value, index, data) {
warning[index] = data[index] - normal[index] - error[index] < 0 ? 0 : data[index] - normal[index] - error[index];
});
myCharts.clear();
option = {
/* 圖表標題 */
title: {
show: true,
text: 'Demo -- 柱狀圖:指定數值範圍內變色(中間漸變色)'
},
/* X 軸 */
xAxis: [{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
position: 'bottom'
}],
/* Y 軸 */
yAxis: [{
show: true,
type: 'value',
max: 300
}],
/* 相關資料 */
series: [
/* 正常範圍資料 */
{
name: 'normal',
type: 'bar', // 折線圖
barWidth: 30, //柱體寬度
stack: 'a', //分組
data: normal,
color: function (p) {
return 'rgb(0,255,0)'; // 綠色
}
},
/* 警告範圍資料 */
{
name: 'warning',
type: 'bar',
barWidth: 30,
stack: 'a', //同一分組 資料疊加
data: warning,
/* 該範圍內顏色為漸變效果 */
/* 漸變的結束色分兩種情況:
1:超過警告值一半:三色漸變,結束顏色為黃色與紅色之間的某種顏色
2:未超過警告值一半:兩個漸變,結束顏色為綠色與黃色之間的某種顏色
★ 並且,三色漸變情況下需要計算恰好到黃色時,黃色所在的位置比例
*/
color: function (p) {
var color;
mid = (errorValue - warningValue) / 2;
//三色漸變
if (warning[p.dataIndex] > mid) {
//顏色範圍 0,255,0 --> 255,255,0 & 255,255,0 --> 255,0,0 255*2
//值範圍 (warningValue, errorValue)
//顏色單位變化(前半段變化固定 只計算後半段(黃 - 紅)變化)
ps = 255 / ((errorValue - warningValue) / 2);
//計算漸變比例
pb = mid / warning[p.dataIndex] * 1.0;
//計算第二段變色
startColor = 'rgb(255,255,0)';//後半段起始色
endColor = 'rgb(255,' + (255 - ((warning[p.dataIndex] - mid) * ps)) + ',0)';//後半段結束色
color = new echarts.graphic.LinearGradient(0, 1, 0, 0, [
{ offset: 0, color: 'rgb(0,255,0)' },
{ offset: pb, color: startColor },
{ offset: 1, color: endColor }
]);
}
//雙色漸變
else {
//顏色範圍 0,255,0 -- > 255,255,0 Y --> G 255
//值範圍 (warningValue, (errorValue-warningValue)/2)
//顏色單位變化
ps = 255 / ((errorValue - warningValue) / 2);
//雙色不需要計算漸變比例
//起始色固定 計算終止色
startColor = 'rgb(0,255,0)';
endColor = 'rgb(' + (ps * warning[p.dataIndex]) + ', 255, 0)'; // G --> Y 255,255,0
//console.log(startColor, endColor);
//返回漸變值
color = new echarts.graphic.LinearGradient(0, 1, 0, 0,
[
{ offset: 0, color: startColor },
{ offset: 0.5, color: endColor }
]
);
}
return color;
}
},
/* 錯誤範圍資料 */
{
name: 'error',
type: 'bar',
barWidth: 30,
stack: 'a',
data: error,
color: 'rgb(255,0,0)'
}]
};