Echarts和highCharts图表使用总结(附AntV)

2,714 阅读6分钟

Echarts:

1.给y轴上间隔线设置成虚线

yAxis: {
            type: 'value',
            boundaryGap: [0, '100%'],
            axisLine: {show: false},
            axisTick: {
                show: false //y轴上不显示刻度
            },
            axisLabel: {           // 坐标轴文本标签,详见axis.axisLabel
                show: true,
                rotate: 0,
                margin: 20,
                textStyle: {       // 其余属性默认使用全局文本样式,详见TEXTSTYLE
                    color: 'rgba(0,0,0,0.65)'
                }
            },
            splitLine:{//间隔线
                show:true,
                lineStyle:{
                    type:'dashed',//设置成虚线
                    color:'#E8E8E8'
                }
            }
        },

2.echarts的x轴和y轴都隐藏

option = {
     xAxis: {
        type: 'category',
        show:false
    },
    yAxis: {
        type: 'value',
        show:false
    },
    series: [{
        symbol: "none",//隐藏折线上的小圆点
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line'
    }]
};

3.设置图表的上下间隔线是实线,其余是虚线

   //把xAxis设为数组,写两个x轴,其余的横向间隔线在y坐标轴设置
	xAxis: [{
		type: 'value',
		name: '',
		splitLine: {
			show: false,
		},
	   },{
	   	type: 'category',
	   }],
		

4.散点图中的气泡图:标记最大值和做标示线(业务需求:筛选出不同类别中最大的那个值并做特殊样式处理,比如加个图片表明是最大值)

series: [{
        markPoint:{//在最大值处加一张图
            symbol : 'image://./static/img/icon-1/symbols-logo-1.png',
	    symbolSize : 10,
	    symbolOffset:[0,'-50%'],
            effect : {
                show : true
             },
	    label:{
	      color:'#FFF',
	      fontStyle:14,
	      align:'center',
	      verticalAlign:'center',
	      position: ['50%', '100%']
	    },
	    data:[{
	    	name: '最大值',
	    	type: 'max',
	    	valueIndex:1
             }],
        },
        markLine:{   //做标记线
                symbol: 'none',
		lineStyle: {
			color: '#5B6DC8',
		},
		label: {
			normal: {
			position: "end",
				backgroundColor: '#101641',
				padding: [10, 20],
				borderRadius: 4,
				color: '#FFF',
				formatter: '{b}',
			},
		},
		animation: false,
		data: [{
			name: 'y轴平均值',
			yAxis: avgY
			},{
			name: 'x轴平均值',
			xAxis: avgX
		}],
         }
    }]

同上:标出最大值(在不同的类别添加标注点,这种写法只能在一个类别中添加一个标注点,可以通过在markPoint中的data设置数组来添加多个标注点,不过每个标注点的样式只能相同,要想在不同的类别中添加多个标注点且每个标注点样式不同,可以用label属性)

var makeMarkPoint = function (index, url, size, offset, coord) {  
				option.series[index].markPoint = {
					symbol: 'image://' + url,  //图片url
					symbolSize: size,  //设置标注图片的大小
					symbolOffset: offset,  //图片位置
					label: {   //标注文字样式
						color: '#FFF',
						fontStyle: 30,
						align: 'center',
						verticalAlign: 'middle',
						position: ['50%', '150%'],
						formatter: '{b}'
					},
					data: [{  //需要进行标注的坐标
						name: domainDataIndex[index],
						coord: coord
					}],
				}
			}
			
makeMarkPoint(index1,'./static/img/top1.png', 40, [0, '-100%'], domainDataCoord[0])
			
var data = [[28604,77,17096869,'11',1990],[31163,77.4,27662440,'22',1990],[1516,68,1154605773,'33',1990]]
    
 //在同一类别下添加多个标注点
    var array1 = [];
	var array2 = [];
	var array3 = [];
	for (var j = 0; j < dataArr.length; j++) { //把数据放在一个加入了图片url的数组中
		if (max1 == dataArr[j]) {
			datatop3Arr[j].push('./static/img/top1.png');
			array1.push(datatop3Arr[j])
		}
		if (max2 == dataArr[j]) {
			datatop3Arr[j].push('./static/img/top2.png');
			array2.push(datatop3Arr[j])
		}
		if (max3 == dataArr[j]) {
			datatop3Arr[j].push('./static/img/top3.png');
			array3.push(datatop3Arr[j])
		}
	}
	var poptotalarray = [];
	poptotalarray = poptotalarray.concat(array1, array2, array3)

 
	var nameforindex = function (str) {
		if (str == '11') return 0
		if (str == '22') return 1
		if (str == '33') return 2
		if (str == '44') return 3
		if (str == '55') return 4
	}
	var yetaiArray1 = []
	var yetaiArray2 = []
	var yetaiArray3 = []
	var yetaiArray4 = []
	var yetaiArray5 = []
	for (var j = 0; j < poptotalarray.length; j++) {
		var index = nameforindex(poptotalarray[j][4]);
		var pop = {
			name: poptotalarray[j][3],
			coord: [poptotalarray[j][0], poptotalarray[j][1]]
		}
		if (index == 0) yetaiArray1.push(pop);
		if (index == 1) yetaiArray2.push(pop);
		if (index == 2) yetaiArray3.push(pop);
		if (index == 3) yetaiArray4.push(pop);
		if (index == 4) yetaiArray5.push(pop);
	}

用label设置图片

(max1,max2,max3为最大的三个值)
    option.series[i].label = {
		show: true,
		position: 'insideTop',//设置位置在中上
		formatter: function (value) {
			var val = value.data[3];
			var strs = val.split(''); //字符串数组
			var str = '';
			for (var i = 0, s; s = strs[i++];) { //文本超过三个字就换行
				str += s;
				if (!(i % 3)) str += '\n'; 
			}
			if (parseInt(value.data[2]) == max1) {  
				return [
					'{topimg1|}',
					'{value|' + str + '}',
				].join('\n');
			} else if (parseInt(value.data[2]) == max2) {
				return [
					'{topimg2|}',
					'{value2|' + str + '}',
				].join('\n');
			} else if (parseInt(value.data[2]) == max3) {
				return [
					'{topimg3|}',
					'{value3|' + str + '}',
				].join('\n');
			}
			return ""
		},
		offset: [0, -18],
		textBorderColor: 'transparent',
		rich: {
			value: {
				lineHeight: 15,
				align: 'center',
				color: '#FFF',
				fontWeight: 'bold',
				fontSize: 16,
				padding: [-30, 0, 0, 0]
			},
			value2: {
				lineHeight: 15,
				align: 'center',
				color: '#FFF',
				fontWeight: 'bold',
				fontSize: 14,
				padding: [-20, 0, 0, 0]
			},
			value3: {
				lineHeight: 15,
				align: 'center',
				color: '#FFF',
				fontWeight: 'bold',
				fontSize: 12,
				padding: [-10, 0, 0, 0]
			},
			topimg1: {
				height: 40,
				align: 'center',
				backgroundColor: {
					image: './static/img/top1.png'
				},

			},
			topimg2: {
				height: 40,
				align: 'center',
				backgroundColor: {
					image: './img/top2.png'
				},
				width: 30,
				height: 30
			},
			topimg3: {
				height: 40,
				align: 'center',
				backgroundColor: {
					image: './static/img/top3.png'
				},
				width: 20,
				height: 20
			}
		}
	};

在AntV中给label文字格式化设置图片

.label('name', {
    labelLine: false, // 不显示文本的连接线
    offset: 30, // 文本距离图形的距离
    htmlTemplate: (text, item, index) => {
      const point = item.point; // 每个弧度对应的点
      let percent = point['percent'];
      percent = (percent * 100).toFixed(2) + '%';
      return '<span class="title" style="display: inline-block;width: 50px;">' + text + '</span><br><span style="color:' + point.color + '">' + percent + '</span>'; // 自定义 html 模板
    }
  });

5.标记点设置成圆环

	option.series[0].markPoint = { 
					symbolSize: 15, 
					symbol: 'circle',
					itemStyle: {
						normal: {
							borderColor: '#45DD54',//环的颜色
							color: "#1B235B",//环内的背景色
							borderWidth: 3, //环的宽度
							label: {
								show: true,
								backgroundColor: '#45DD54',
								padding: [6, 20],
								borderRadius: 4,
								color: 'white',
								lineHeight: 20,
								position: 'top',
								formatter: '{title|{b}}\n{num|{c}} %',
								rich: {
									title:{
										fontWeight: 'bold',
										color: '#fff',
										fontSize:16
									},
									num: {
										fontWeight: 'bold',
										color: '#fff',
										fontSize:20
									},

								}
							}
						},
					},
					effect: {
						show: true,
						shadowBlur: 0
					},
					data: [{
						name: '',
						value: pointY,
						xAxis: dateData[20],
						yAxis: pointY
					}, ],

				},

6.给标记点设置背景图片(适用于背景是对话框有箭头的样式)

itemStyle: {
		normal: {
			label: {
				show: true,
				backgroundColor: {
				    image:'./static/img/symbols-up.png',//设置背景图
				},
			}
		}
	}	

7.柱状图的柱子设置不同的颜色

series : [
        {
            name:'直接访问',
            type:'bar',
            barWidth: '60%',
            color: function(val){
                if(val.value == 220){ //位于某个特定值的柱子设置一个特殊的颜色
                    return "red"  
                }
                return "green";    
            },
            data:[10, 52, 200, 334, 390, 330, 220]
        }
    ]

8.漏斗图左部分文字左对齐

option = {
    grid: {
        left: 100
    },
    toolbox: {
        show: true,
        feature: {
            saveAsImage: {}
        }
    },
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: function(a,ix){
                return ix;
            }
        },
        splitLine: {
            lineStyle: {
                type: 'dashed'
            }
        }
    },
    xAxis: {
        show: false
    },
    series: [
        {
            name: 'City Gamma',
            type: 'bar',
            data: [0, 0, 0]
        },
        {
            name: '实际',
            type: 'funnel',
            left: '10%',
            width: '80%',
            maxSize: '80%',
            label: {
                normal: {
                    position: 'inside',
                    formatter: '{c}%',
                    textStyle: {
                        color: '#fff'
                    }
                },
                emphasis: {
                    position:'inside',
                    formatter: '{b}实际: {c}%'
                }
            },
            itemStyle: {
                normal: {
                    opacity: 0.5,
                    borderColor: '#fff',
                    borderWidth: 2
                }
            },
            data: [
                {value: 30, name: ''},
                {value: 10, name: ''},
                {value: 5, name: ''},
                {value: 50, name: ''},
                {value: 80, name: ''}
            ]
        }
    ]
};

9.散点图设置点均匀分布

是否是脱离 0 值比例。设置成 true 后坐标刻度不会强制包含零刻度。在双数值轴的散点图中比较有用。

{
    scale:true
}

也可以设置x轴和y轴的最小最大值,达到自己想要的效果

10.设置echarts图表隔一段时间刷新

setInterval(function(){
	refresh.call(me);
}, echartsRefreshInterval);

var refresh = function(){
	var div = this.node.root.insertBefore(document.createElement("div"), this.node.echarts);
	$(div).css({
		position: "absolute",
		top: "0",
		left: "0",
		right: "0",
		bottom: "0"
	});
	this.dom.removeDomNode(this.node.echarts);
	this.node.echarts = div;
	this.eChart = echarts.init(this.node.echarts);
	this.eChart.setOption(this.currData, true);
};

11.气泡图数据多,气泡重叠在一起的问题

可以统一给所有气泡x轴的数据增加20,帮助分散

12.二级图例

    <div
        class="item"
        v-for="(item, index) in arr"
        :key="index"
        :class="{ isSelected: index == indexSelected }"
        @click="filter(item, index)"
    >
        <div
          class="item-chunk"
          :style="{ background: `${indexSelected == index && item.isSelect ? item.color : '#999'}` }"
        ></div>
        <div class="item-title">{{ item.title }}</div>
    </div>
filter(code, index) {
      // myChart 的参数
      code.isSelect = !code.isSelect
      this.indexSelected = index
      var options = this.chartColumn.getOption()
      var selectLegend = options.legend
      for (var i = 0; i < this.arr.length; i++) {
        if (i !== index) this.arr[i].isSelect = false
      }

      for (const key in selectLegend) {
        if (code.isSelect && selectLegend[key].id === code.title) {
          selectLegend[key].show = true
        } else {
          selectLegend[key].show = false
        }
      }
      this.chartColumn.setOption(options, true) // 重新渲染该图片
    },

highCharts

1.设置y轴间隔线为虚线

yAxis: {
        gridLineDashStyle: 'ShortDash',//网格线样式
       },

2.dataLabels线太长导致图片宽度小时,label自动变省略号看不到

plotOptions: {
	pie: {
		dataLabels: {
			enabled: true,
			format: '{point.name}',
			style: {
				color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
				fontSize: '12px',
				fontWeight: 'normal'
			},
			distance:10 //设置distance改变指示线的长度
		},
		showInLegend: true,
		startAngle: 0, // 圆环的开始角度
		endAngle: 360,    // 圆环的结束角度
		center: ['50%', '50%'],
                size:this.pieSize
	}
},

3.在y轴添加标记线(比如预警线)

plotLines: [
            {
                color: "#BFBFBF",
                dashStyle: "dash",
                width: 1,
                value: 24304,
                label: {
                    useHTML:true,
                    text: "预警线<br/>30万",
                    align: "right",
                    style: {
                        color: "#919191",
                        fontSize: "10px"
                    },
                    x:10
                },
                zIndex:9999
            }
        ]