echart 绘制k线图
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script> <title>echart.html</title> </head> <body> <div id="main" style="width: 100px;height:40px;border: 1px dashed #000;margin: 20px;"></div> <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); //generateOHLC 产生随机数组[日期,开盘,最高,最低,关盘],不用去研究; var data = generateOHLC(2000); var option = { dataset: { source: data }, tooltip: { trigger: 'axis', axisPointer: { type: 'line' } }, grid: [ { left: 0, right: 0, top: 0, bottom:0 } ], xAxis: [ { show:false, type: 'category', scale: true, boundaryGap: false, splitNumber: 20, min: 'dataMin', max: 'dataMax' } ], yAxis: [ { show:false, scale: true } ], series: [ { type: 'candlestick', itemStyle: { color: '#00B2D9', color0: '#00B2D9', borderColor: '#00B2D9', borderColor0: '#00B2D9' }, //此处0位数组的第一位即第一维度展示在x轴上 //type: 'candlestick'默认的维度是0-'date', 1-'open', 2-'close', 3-'highest', 4-'lowest' encode: { x: 0, //type: 'candlestick' 的y必须为4个否则报错; //这里的排序针对tooltip的展示,当鼠标放置在图上,展示顺序的改变,并不影响k线图的展示 //若只想展示open,close,则设置为[1,2,1,2] //[1,4,3,2]表示tooltip弹框先展示open,再展示lowest,再展示highest,最后close y: [1,4,3,2] } } ] }; function generateOHLC(count) { console.log(count); var data = []; var xValue = +new Date(2011, 0, 1); var minute = 60 * 1000; var baseValue = Math.random() * 12000; var boxVals = new Array(4); var dayRange = 12; for (var i = 0; i < count; i++) { baseValue = baseValue + Math.random() * 20 - 10; for (var j = 0; j < 4; j++) { boxVals[j] = (Math.random() - 0.5) * dayRange + baseValue; } boxVals.sort(); var openIdx = Math.round(Math.random() * 3); var closeIdx = Math.round(Math.random() * 2); if (closeIdx === openIdx) { closeIdx++; } var volumn = boxVals[3] * (1000 + Math.random() * 500); // ['open', 'close', 'lowest', 'highest'] // [1, 4, 3, 2] data[i] = [ echarts.format.formatTime('yyyy-MM-dd\nhh:mm:ss', xValue += minute), +boxVals[openIdx].toFixed(2), // open +boxVals[3].toFixed(2), // highest +boxVals[0].toFixed(2), // lowest +boxVals[closeIdx].toFixed(2) // close ]; } return data; function getSign(data, dataIndex, openVal, closeVal, closeDimIdx) { var sign; if (openVal > closeVal) { sign = -1; } else if (openVal < closeVal) { sign = 1; } else { sign = dataIndex > 0 ? (data[dataIndex - 1][closeDimIdx] <= closeVal ? 1 : -1) : 1; } return sign; } } myChart.setOption(option); </script> </body> </html>