基于Echart实现的自定义瀑布图 demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义测试Echart系列</title>
<!-- 引入Echarts -->
<script src="./echarts.js"></script>
<style>
#root{
500px;
height: 300px;
}
body{
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/javascript">
var chart = echarts.init(document.querySelector("#root"));
var data = [
{name:"aaa",value:100},
{name:"bbb",value: -10},
{name:"ccc",value: 50},
{name:"ddd",value: -20},
{name:"eee",value:-40},
{name:"fff",value:80},
// {name:"ggg",value:160},
];
var legend = {
start: "统计期量",
end:"统计期量",
minus:"回落",
positive:"增加"
}
// 获取系列的函数 可以配色
function getSeries(arr, renderItemName, legend){
var sum = 0;
var series = [];
arr.forEach( (item, index) => {
sum += item.value;
var temp = {
type: 'custom',
name: item.name,
renderItem: renderItemName,
label:{
show: true,
formatter: (p)=>{
return Math.abs(p.value[0]);
}
},
data: [{ value:[ item.value, sum] }],
}
if(index == arr.length -1){
temp.id = 'end';
temp.data[0].value[1] = temp.data[0].value[0];
temp.data[0].value.push(arr[0].value);
}
if(legend){
if(index == 0){
temp.name = legend.start;
}else if(index == arr.length -1){
temp.name = legend.end;
}else if(item.value < 0){
temp.name = legend.minus;
}else{
temp.name = legend.positive;
}
}
series.push(temp);
});
return series;
}
function renderItem(params, api) {
var categoryIndex = params.seriesIndex; // 类目轴的索引
var width = api.size([0, 1])[0] * 0.6; // 计算宽度
// 计算 实际点
var start = api.coord([categoryIndex, api.value(1)]);
var end = api.coord([categoryIndex, 0]);
var height = end[1] - start[1];
var x = start[0] - width/2;
var y = start[1];
var lineY;
var startY;
if (categoryIndex !== 0 && params.seriesId != "end") {
// 前一个点的坐标
var perStart = api.coord( [categoryIndex - 1, api.value(1) - api.value(0)] );
var perEnd = api.coord( [categoryIndex - 1, 0] );
height = height - ( perEnd[1] - perStart[1] );
// 处理负值
if (height < 0) {
height = -height;
y = y - height;
}
if(api.value(0) <= 0){
lineY = y + 0.5;
} else{
lineY = y + height - 0.5;
}
}else{
lineY = y + 0.5;
}
var rectShape = echarts.graphic.clipRectByRect({
x,y,width,height,
}, {
x: params.coordSys.x,
y: params.coordSys.y,
params.coordSys.width,
height: params.coordSys.height
});
return {
type: 'rect',
shape: rectShape,
style: api.style(),
};
}
option = {
grid:{
height: 200
},
xAxis: {
type: 'category',
},
yAxis: {
type: 'value',
splitLine: {
show: false
},
max: 200
},
tooltip:{
show: true,
formatter: (p)=>{
return p.seriesName + ": " + Math.abs(p.data.value[0]);
}
},
legend : {
show:true,
},
};
option.series = getSeries(data,renderItem,legend);
option.xAxis.data = data.map( item=> item.name);
chart.setOption(option);
</script>
</body>
</html>