echarts——legend图例颜色设置,legend数组形式展示
场景`renderBar`函数调整场景
最近在写看板的时候,遇到一个小细节,就是当折线图展示图表时,线的颜色不够明显,导致视觉上不突出。
问题效果图如下:
修改后的效果图:
还是拿前几天文章中的renderBar
渲染图表的函数来处理.
renderBar
函数调整
如果要保证图例颜色各不相同,可以给legend设置成数组的形式。主要代码如下:
let legend = [];series.forEach((item, index) => {legend.push({name: item.name,textStyle: {color: color[index] },});});console.log('legend', legend);
完成代码如下:
function renderBar(dom, xAxis, series, color, nameArr) {let legend = [];series.forEach((item, index) => {legend.push({name: item.name,textStyle: {color: color[index] },});});console.log('legend', legend);var option = {color: color,legend: {left: 'right',textStyle: {color: '#fff',},data: legend,},grid: {x: 60,x2: 40,y: 60,y2: 30,},xAxis: {type: 'category',data: xAxis,axisLabel: {textStyle: {color: '#666666',},},},yAxis: [{name: nameArr[0],nameTextStyle: {color: '#fff',},max: nameArr[0] && nameArr[0].indexOf('百分率') > -1 ? 100 : null,axisLabel: {textStyle: {color: '#fff',},formatter: (c) => {if (nameArr[0] && nameArr[0].indexOf('百分率') > -1) {return c + '%';} else {return c;}},},axisLine: {show: false,},axisTick: {show: false,},splitLine: {show: true,lineStyle: {type: 'solid',color: '#333',},},},{name: nameArr[1],nameTextStyle: {color: '#fff',},axisLabel: {textStyle: {color: '#666666',},},axisLine: {show: false,},axisTick: {show: false,},splitLine: {show: false,},},],series: series,};option && dom.setOption(option);}
使用渲染函数的方法如下:
var chartDom1 = document.getElementById('barId1');var myChart1 = echarts.init(chartDom1);renderBar(myChart1,xAxis1,[{name: '复购率',type: 'line',data: yAxis1,symbolSize: 10,itemStyle: {normal: {borderColor: '#f90',borderWidth: 2,lineStyle: {width: 3, // 0.1的线条是非常细的了,color: '#f90',},label: {show: true, //开启显示position: 'top',formatter: '{c}%',textStyle: {color: '#fff',fontSize: 16,},},},},areaStyle: {color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0, color: '#f90' },{offset: 0.2, color: '#f90' },{offset: 1, color: 'transparent' },]),},},{name: '流失率',type: 'line',symbolSize: 10,data: yAxis2,itemStyle: {normal: {borderColor: '#227bff',borderWidth: 2,lineStyle: {width: 3, // 0.1的线条是非常细的了,color: '#4992FF',},label: {show: true, //开启显示position: 'top',formatter: '{c}%',textStyle: {color: '#fff',fontSize: 16,},},},},areaStyle: {color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0, color: '#4992FF' },{offset: 0.2, color: '#4992FF' },{offset: 1, color: 'transparent' },]),},},],['#f90', '#4992FF'],['单位:百分率', '']);