注意:本文为vue的写法
背景:页面根据后台返回的数组,动态生成渐变堆叠折线图,有几组数据则生成对应的几条折线图。
效果图:
下面分别从图例(legend)、提示框(tooltip)、series等各方面介绍配置参数。
折线图的色彩池
const rgbColorList = [
"61, 115, 255",
"64, 206, 210",
"235, 119, 137",
"151, 121, 255",
"247, 181, 0",
"56, 196, 247",
"255,85,172",
"131,120,234",
"50,197,233",
"231,188,243",
];
本示例的数据源格式:
valueArr: [
{
label:"demo1",
valueList: [0.23,0.89,2.3,2,...]
},
...
]
1、图例(legend)
legend: {
orient: "vertical",
icon: "circle",
top: "center",
left: "82%",
itemWidth: 8,
itemGap: 20,
data: this.valueArr.filter(function (item) {
return item.label;
}),
textStyle: {
color: "#888"
}
}
orient
:图例列表的布局朝向, 默认为 ‘horizontal’icon
:图例项的 icon, 其他值参考echarts iconitemWidth
:图例标记的图形宽度itemGap
:图例每项之间的间隔,横向布局时为水平间隔,纵向布局时为纵向间隔
2、提示框(tooltip)
tooltip: {
trigger: "axis",
formatter: this.formateTooltip,
}
// 格式化tooltip,让提示框内每一项都与图例icon颜色对应,且单独一行显示
function formateTooltip (params) {
let html = `${params[0]&¶ms[0].name}<br/>`, dataVal = "";
const that = this;
params.forEach(v => {
dataVal = v.value;
html += `<div style="color: #fff;font-size: 14px;line-height: 24px">
<span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(${colorRgbList[v.componentIndex]});"></span>
${v.seriesName}
<span style="margin-left:10px;">${dataVal}</span></div>`;
});
return html;
}
3、series,series配置是实现堆叠与渐变的关键,生成堆叠的折线条数(n)与series子元素数量相等(可以理解为:n === series.length)
echarts.graphic.LinearGradient
:线性渐变,前四个参数分别是 x0, y0, x2, y2, 范围从 0 -1,相当于在图形包围盒中的百分比,如果 globalCoord 为true
,则该四个值是绝对的像素位置,更多详情可以查看echarts color。
代码如下:
this.valueArr.map((item, index) => {
series[index] = {
type: "line",
name: item.label,
smooth: true,
itemStyle: {
normal: {
color: `rgba(${colorRgbList[index]}, 1)`,
},
},
areaStyle: {
normal: {
color: new echarts.graphic.LinearGradient( // 实现渐变的配置
0, 0, 0,1,
[
{
offset: 0,
color: `rgba(${colorRgbList[index]}, 0.2)`,
},
{
offset: 1,
color: `rgba(${colorRgbList[index]}, 0)`,
},
],
false
),
shadowColor: `rgba(${colorRgbList[index]}, 0.05)`,
shadowBlur: 20,
},
},
data: item.valueList,
};
});