echarts 折線圖數據繪製一個K線圖表()

項目中客戶有這個需求(主要想看漲跌),這裏記錄一下。效果圖 :

簡單的k線圖需要四條數據(//開盤(open),收盤(close),最低(lowest),最高(highest))。開盤價取折線圖的實時價,收盤價也取折線圖的實時價,最低最高在隨機取值就會有折線圖的感覺(沒有中間的塊,只判斷漲跌)。

折線圖數據實時刷新,漲跌echarts會判斷(開盤價和收盤價一樣,後一條數據的值比前一條數據的值大,判爲漲,否則爲跌)

主要代碼:

getLine() {
	let echart = document.getElementById("goldEchart");
	this.goldEchart = echarts.init(echart);

	let dateList = [];
	let valueList = [];
	let data = []
	let dates = []

	//this.lineList 後臺數據格式如下:
	//id: 9031
	//latestpri: "1510.64"
	//limit: "-0.16%"
	//time: "2019-11-01 19:20:24"
	//dat是一個時期格式化函數

	this.lineList.forEach((value, key) => {
		valueList.push(Number(value.latestpri))
		dates.push(dat(new Date(value.time), 'hh:mm'))
		let minpri = Number(value.latestpri) - Math.random() * 0.05
		let maxpri = Number(value.latestpri) + Math.random() * 0.05
		data.push([value.latestpri, value.latestpri, Number(minpri).toFixed(2), Number(maxpri).toFixed(2)])
	})
	//價格最小值(y軸最小刻度)
	let min = Math.round(Math.min.apply(Math, valueList));
	let max = Math.round(Math.max.apply(Math, valueList));
	let option = {
		animation: false,
		tooltip: {
			trigger: "axis",
			type: 'none',
			//提示框背景色
			backgroundColor: '#DA5151',
			//提示框樣式
			formatter: function(params) {
				params = params[0];
				return params.name + '</br><p style="background:#fff;display:inline-block;width:9px;height:9px;border-radius:50%"></p> ' + params.value[1] + '<span style="font-size:12px">' + ' ' + '</span>';
			},
			axisPointer: {
				type: 'none', //去掉提示框豎線
			}
		},
		xAxis: [{
			splitNumber: 5,
			type: 'category',
			boundaryGap: false,
			axisLine: {
				show: false,
				onZero: false,
				lineStyle: {
					color: '#999'
				}
			},
			axisLabel: {
				interval: 'auto', //橫座標間隔
			},
			axisTick: { //x軸刻度線
				show: false
			},
			data: dates
		}],
		yAxis: [{
			splitNumber: 5,
			type: 'value',
			max: max + 0.5,
			min: min - 0.5,
			axisLabel: {
				formatter: function(value, index) {
					return value.toFixed(2);
				}
			},
			axisLine: {
				show: false, //隱藏縱軸座標線
				onZero: false,
				lineStyle: {
					color: '#999'
				}
			},
			axisTick: { //y軸刻度線
				show: false
			},
			splitLine: {
				show: true,
				lineStyle: {
					color: '#555',
					type: 'dotted'
				}
			},
		}],
		grid: [{
			top: 20,
			left: 55,
			right: 15,
			bottom: 30,
		}],
		series: [{
			type: 'candlestick',
			name: '日K',
			data: data,
			itemStyle: {
				normal: {
					color: '#d52c21',
					color0: '#5ab13e',
					borderColor: '#d52c21',
					borderColor0: '#5ab13e'
				},
			},
		}]
	};

	if(this.goldEchart) {
		this.goldEchart.clear() //clear 重新繪製
		this.goldEchart.setOption(option);
	}

	//顯示提示框
	this.goldEchart.dispatchAction({
		type: 'showTip',
		seriesIndex: 0, // 顯示第幾個series
		dataIndex: data.length - 1 // 顯示第幾個數據
	});
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章