Echarts时间坐标轴刻度的改进和优化
問題介紹:
Echarts插件的坐標(biāo)軸類型主要分為時間(time)、數(shù)值(value)、對數(shù)(log)、類目(category)四大類,當(dāng)采用二維的直角坐標(biāo)系時,一般x軸通過采用類目軸,而y軸通常采用value軸。官方的有關(guān)的直角坐標(biāo)系例子,大多遵循這個原則配置的。這樣配置其實(shí)只適用于離散型數(shù)據(jù),而對于時間型數(shù)據(jù),雖然有時間軸的支持,但是效果卻差強(qiáng)人意,甚至存在展示的缺陷。
如圖1所示為日的時間型數(shù)據(jù),從圖上可以看出柱狀圖的柱子跟y軸有重疊,x軸刻度值少的問題。如圖2、3所示為月和年的時間型數(shù)據(jù),問題跟圖1差不多,但還有一個不一樣的問題,就是刻度值,不管是月還是年的數(shù)據(jù),刻度值都顯示的日的刻度值,這個對于用戶來說,體驗(yàn)應(yīng)該是不好的。更好的體驗(yàn)應(yīng)該是,月的時間型數(shù)據(jù),顯示的刻度值應(yīng)該都是月的刻度值;年的時間型數(shù)據(jù),顯示的應(yīng)該都是年的刻度值。如圖4、5、6,是本人優(yōu)化和處理后的顯示效果圖。
總的來說,主要存在以下三個問題
(1)不同時間格式下,計算出來的刻度不符合預(yù)期;
(2)數(shù)據(jù)的最小值容易與坐標(biāo)軸重疊,最大值容易顯示在圖表之外;
(3)計算出來的刻度個數(shù)偏少,數(shù)據(jù)之間容易重疊。
圖2 時間格式為月的時間軸展示
圖3 時間格式為年的時間軸展示
圖4 時間格式為日的時間軸展示
圖5 時間格式為月的時間軸展示
圖6 時間格式為年的時間軸展示
Echarts時間型刻度的計算方法:
通過閱讀Echarts源碼,可以了解Echarts對于時間型刻度的計算方法: 在Echarts的架構(gòu)中, echarts/scale/Time模塊負(fù)責(zé)對時間刻度進(jìn)行處理和計算,但求解刻度的算法還是采用線性比例尺的算法,即將時間型數(shù)據(jù)轉(zhuǎn)為時間戳(變?yōu)榧償?shù)字),然后通過線性比例尺求刻度的方法計算得出時間戳類型的刻度,最后通過時間轉(zhuǎn)換函數(shù),將時間戳刻度,轉(zhuǎn)為時間型刻度。而且在源碼里面,將數(shù)據(jù)的最小值和最大值,默認(rèn)設(shè)置為刻度的最小值和最大值,并且刻度個數(shù)通常只有五個,偏少。
改進(jìn)和優(yōu)化方法:
針對前文總結(jié)出的三點(diǎn)缺陷,現(xiàn)提出以下的改進(jìn)和優(yōu)化方法:
(1)針對不同時間格式下刻度的計算問題,借鑒d3.js的時間比例尺接口和方法,并將其整合到Echarts源碼中。d3.js針對不同時間格式,采用不同函數(shù)計算時間刻度,針對年、月、日、小時分別有year、month、day、hour等函數(shù)。不同時間格式函數(shù)處理刻度方法稍有不同。具體方法下文會詳細(xì)介紹。
(2)針對最小值容易與坐標(biāo)軸重疊,最大值容易顯示在圖形之外問題。采用保留刻度法予以解決。保留刻度法:即數(shù)據(jù)最小值與刻度最小值之差為正且小于步長20%,或者數(shù)據(jù)最小值與刻度最小值之差為負(fù),則最小刻度需要再向下增加一個刻度;若數(shù)據(jù)最大值與刻度最大值之差為負(fù)且絕對值小于步長20%,或者數(shù)據(jù)最小值與刻度最小值之差為正, 則最大刻度需要再向上增加一個刻度。
(3)針對計算出來的刻度個數(shù)偏少問題,采用自適應(yīng)寬度的方法,力求最大的刻度個數(shù)。
規(guī)定刻度標(biāo)簽的旋轉(zhuǎn)45度,每一個標(biāo)簽占用30px的寬度,這樣,如果圖表的寬為600px,則理論上可以在坐標(biāo)軸上最大放置20個刻度。
具體實(shí)現(xiàn):
(1)通過調(diào)試d3.js源碼和研究,發(fā)現(xiàn)d3.js處理時間比例尺的接口主要是以下代碼,代碼中newInterval可以看做一個構(gòu)造函數(shù),傳入不同的參數(shù),都會返回interval對象,但interval對象的方法卻因?yàn)閰?shù)和變量值的不一樣,而有不同的功能。比如:year對象專門處理只與年相關(guān)的比例尺,month對象則專門處理與月相關(guān)的比例尺,minute對象則專門處理與分鐘相關(guān)的比例尺…這些對象有1個方法,是計算比例尺的關(guān)鍵,它就是range(start,stop,step)函數(shù),它接受三個參數(shù),start:數(shù)據(jù)的開始點(diǎn)(數(shù)據(jù)最小值),stop:數(shù)據(jù)的終點(diǎn)(數(shù)據(jù)最大值),step:相鄰刻度的步長。以年為例,假設(shè)現(xiàn)在數(shù)據(jù)最小值是2011,最大值是2028年,步長是2。則通過range函數(shù),計算出來的刻度是[1293811200000, 1356969600000, 1420041600000, 1483200000000, 1546272000000, 1609430400000, 1672502400000, 1735660800000, 1798732800000],接著再將時間戳格式化[“2011-01-01 00:00:00”, “2013-01-01 00:00:00”, “2015-01-01 00:00:00”, “2017-01-01 00:00:00”, “2019-01-01 00:00:00”, “2021-01-01 00:00:00”, “2023-01-01 00:00:00”, “2025-01-01 00:00:00”, “2027-01-01 00:00:00”]。從結(jié)果可以看出,計算出來的刻度值只是在年份上遞增,滿足我們的預(yù)期,同理,其他月、日、小時的時間格式比例尺計算方法也跟這個類似。
(2)針對第二個問題的解決方法,主要是對(1)中算出的刻度進(jìn)一步處理,說白了,就是給刻度的兩個端點(diǎn)適量留一些空白,以便不影響柱狀圖等圖形顯示。具體代碼如下所示:
/*** 優(yōu)化并調(diào)整刻度的最大刻度和最小刻度,* 若存在,直接返回刻度值* @param {Object} params * @param {Array.<Number>} params.ticks: 包含刻度的數(shù)組* @param {Array.<Number>} params.extent: 最大刻度和最小刻度數(shù)組* @param {Array.<Number>} params.niceTickExtent: 更新后的最大刻度和最小刻度數(shù)組* @param {Number} params.splitNum: 刻度軸的分割數(shù)目* @param {Function} params.offset: 時間軸時,為時間的偏移函數(shù);數(shù)值軸時為null* @param {Number} params.step: 時間軸時,刻度之間的步長* @param {Number} params.intervalPrecision: 數(shù)值軸時,刻度值的精度*/helper.adjustTickExtent = function (params) {var ticks = params.ticks,extent = params.extent,niceTickExtent = params.niceTickExtent,splitNum = params.splitNum;var context = this;var interval;var name = extent[0] + '@#' + extent[1] + '&' + splitNum;// 緩存存在直接返回 if (this.cache[name]) {return this.cache[name];} if (processOnlyNum (params, context)) {return ticks;} preprocessTicks(params); calTickMin(params, extent[0]);calTickMax(params, extent[1]); setAdjustExtent.call(this, niceTickExtent, extent, ticks, splitNum);return ticks;/*** 當(dāng)數(shù)據(jù)最大值和最小值相等時* 此時刻度值數(shù)目只有三個* @param {Object} params: 包含參數(shù)值的對象* @param {Object} context: 執(zhí)行環(huán)境的上下文*/function processOnlyNum (params, context) {var ticks = params.ticks;var offset = params.offset;var adjustInterval = 1;var extent = params.extent;var step = params.step;var onlyNum = params.onlyNum;var intervalPrecision = params.intervalPrecision;//onlyNum表示數(shù)據(jù)只有一條if (onlyNum != null) {if (offset === null) {ticks.length = 0;adjustInterval = extent[1] - extent[0];ticks[0] = extent[0];ticks[1] = extent[1];onlyNum == extent[0] ? ticks.unshift(extent[0] - adjustInterval) : ticks.push(extent[1] + adjustInterval); } else {ticks.length = 0;ticks[0] = offset(onlyNum, -step).getTime(); ticks[1] = onlyNum;ticks[2] = offset(onlyNum, step).getTime(); } setAdjustExtent.call(context, niceTickExtent, extent, ticks, splitNum);return true;} return false;}/*** 預(yù)處理刻度,功能:*(1)移除刻度中數(shù)值等于extent[0]和extent[1]的刻度*(2)將只包含一個刻度和兩個刻度的刻度數(shù)組擴(kuò)展成多個* @param {Object} params: 包含各種參數(shù)的對象*/function preprocessTicks(params) { var ticks = params.ticks;var offset = params.offset;var extent = params.extent;var step = params.step;var intervalPrecision = params.intervalPrecision;//ticks等于1,只有可能是時間軸的情況if (ticks.length == 1) { ticks.unshift(offset(ticks[0], -step).getTime()); ticks.push(offset(ticks[ticks.length - 1], step).getTime()); } else if ((ticks.length == 2 || ticks.length == 3) && offset == null) {//當(dāng)刻度的最小值是數(shù)據(jù)的最小值時,根據(jù)step求出最小刻度tick = ticks[0]; if (tick == extent[0] && (tick % step != 0)) {tick = roundNumber(tick - (tick % step) , intervalPrecision);ticks[0] = tick; }//當(dāng)刻度的最大值是數(shù)據(jù)的最大值時,根據(jù)step求出最大刻度tick = ticks[ticks.length - 1];if (tick == extent[1] && (tick % step != 0)) { tick = roundNumber(tick + step - (tick % step) , intervalPrecision);ticks[ticks.length - 1] = tick;} } else if (ticks.length > 3) {ticks[0] == extent[0] && ticks.shift();ticks[ticks.length - 1] == extent[1] && ticks.pop();} }/*** 計算刻度的最小刻度* @param {Object} params: 包含各種參數(shù)的對象* @param {Number} min:數(shù)據(jù)的最小值 */ function calTickMin(params, min) { var ticks = params.ticks;var offset = params.offset; var step = params.step; var intervalPrecision = params.intervalPrecision; var interval = offset === null ? step : (ticks[1] - ticks[0]); var i = 0, tickMin, differ, tick; while (true) {i++;if (i == 3) {break;}tickMin = ticks[0];differ = min - tickMin; if (differ > 0 && differ >= interval * 0.2 ) { break;} /** 若數(shù)據(jù)最小值與刻度最小值之差為正且小于步長20%,* 或者數(shù)據(jù)最小值與刻度最小值之差為負(fù)* 則最小刻度需要再向下增加一個刻度 */ if ((differ > 0 && differ < interval * 0.2) || differ <= 0) { //數(shù)值軸if (offset == null) {tick = roundNumber(tickMin - step, intervalPrecision);//時間軸} else {tick = offset(tickMin, -step).getTime();} ticks.unshift(tick); }} }/*** 計算刻度的最小刻度* @param {Object} params: 包含各種參數(shù)的對象* @param {Number} min:數(shù)據(jù)的最小值 */ function calTickMax(params, max, interval) {var ticks = params.ticks;var offset = params.offset; var step = params.step; var intervalPrecision = params.intervalPrecision;var interval = offset === null ? step : (ticks[1] - ticks[0]); var i = 0, tickMax, differ, tick; while (true) { i++; //防止陷入死循環(huán)if (i == 3) {break;} tickMax = ticks[ticks.length - 1];differ = max - tickMax;if (differ < 0 && Math.abs(differ) >= interval * 0.2) { break;}/** 若數(shù)據(jù)最大值與刻度最大值之差為負(fù)且絕對值小于步長20%,* 或者數(shù)據(jù)最小值與刻度最小值之差為正* 則最大刻度需要再向上增加一個刻度 */ if (differ >= 0 || (differ < 0 && Math.abs(differ) < interval * 0.2)) {if (offset == null) {tick = roundNumber(tickMax + step, intervalPrecision);} else {tick = offset(tickMax, step).getTime();}ticks.push(tick); } }}/*** 設(shè)置extent,并存入緩存* @param {Array} niceTickExtent* @param {Array} extent* @param {Array} ticks* @param {Array} splitNum*/function setAdjustExtent(niceTickExtent, extent, ticks, splitNum) {//修正軸的extent niceTickExtent[0] = extent[0] = ticks[0];niceTickExtent[1] = extent[1] = ticks[ticks.length - 1]; var name = extent[0] + '@#' + extent[1] + '&' + splitNum;this.cache[name] = ticks;} };(3)第三個問題,相對來說,簡單很多,采用比較暴力的方法,規(guī)定標(biāo)簽統(tǒng)一傾斜45度展示,每一個標(biāo)簽在x軸上占用40px。這樣可以計算出一根軸上最大容納的標(biāo)簽數(shù)目。方法主要擴(kuò)展在axisHelper對象上。
/*** 計算出軸能容納的最大標(biāo)簽個數(shù)* @param {Number} width:軸的總寬* @return {Number} num: 容納的標(biāo)簽數(shù)目*/axisHelper.getMaxTickNum = function (width) {var perWidth = 40px;var num = Math.floor(width / perWidth);num = num < 1 ? 1 : num;return num;};axisHelper.niceScaleExtent = function (scale, model) {var extent = axisHelper.getScaleExtent(scale, model);var axis = model.axis;var fixMin = model.getMin() != null;var fixMax = model.getMax() != null;var splitNumber = model.get('splitNumber');var mulDimension = model.get('mulDimension');// 時間軸刻度自適應(yīng)if (axis.model.get('tickMax') && axis.type != 'category' && axis.dim == 'x') {splitNumber = axisHelper.getMaxTickNum(axis._extent[1] - axis._extent[0], mulDimension); scale.splitNumber = splitNumber;}if (scale.type === 'log') {scale.base = model.get('logBase');} scale.setExtent(extent[0], extent[1]);scale.niceExtent({splitNumber: splitNumber,fixMin: fixMin,fixMax: fixMax,minInterval: scale.type === 'interval' ? model.get('minInterval') : null});// If some one specified the min, max. And the default calculated interval// is not good enough. He can specify the interval. It is often appeared// in angle axis with angle 0 - 360. Interval calculated in interval scale is hard// to be 60.// FIXMEvar interval = model.get('interval');if (interval != null) {scale.setInterval && scale.setInterval(interval);}};(4)為了實(shí)現(xiàn)這些問題,還有一些初始化工作需要處理,主要有一下代碼實(shí)現(xiàn):
/*** 根據(jù)條件計算出最佳的時間刻度值* @param {Object} params: 包含參數(shù)的集合* @param {Array} params.extent: 刻度的范圍* @param {Array} params.niceTickExtent: 更新后的刻度范圍* @param {Number} params.splitNum: 刻度分割數(shù)目* @param {String} params.defaultFormat: 初始的時間格式* @param {Number} params.onlyNum: 是否只有單個數(shù)值 */helper.processTimeTicks = function (params) {var ticks = [], timeIntervalPro;var extent = params.extent;var splitNum = params.splitNum;var format = selectTimeFormat(extent, splitNum, timeInterval, params.defaultFormat);timeIntervalPro = Math.ceil(timeInterval[format].count(extent[0], extent[1]) / splitNum);timeIntervalPro = timeIntervalPro < 1 ? 1 : timeIntervalPro;ticks = timeInterval[format+'s'](extent[0], extent[1], timeIntervalPro);//調(diào)整刻度的最大刻度和最小刻度ticks = this.adjustTickExtent({ticks: ticks,extent: extent, niceTickExtent: params.niceTickExtent,splitNum: splitNum,offset: timeInterval[format].offset,step: timeIntervalPro,onlyNum: params.onlyNum});return ticks;/*** 判斷使用哪種時間格式求時間刻度* @param {Array} extent: 刻度的范圍* @param {Number} splitNum: 刻度分割數(shù)目* @param {Function} timeInterval: 處理時間刻度的函數(shù)集合* @param {String} defaultFormat: 初始的時間格式*/function selectTimeFormat(extent, splitNum, timeInterval, defaultFormat) {var format = 'timeSecond';if (defaultFormat == 'timeYear') {return 'timeYear';}if (timeInterval.timeYear.count(extent[0], extent[1]) >= splitNum) {format = 'timeYear';} else if (timeInterval.timeMonth.count(extent[0], extent[1]) >= splitNum) {format = 'timeMonth';} else if (timeInterval.timeDay.count(extent[0], extent[1]) >= splitNum) {format = 'timeDay';} else if (timeInterval.timeHour.count(extent[0], extent[1]) >= splitNum) {format = 'timeHour';} else if (timeInterval.timeMinute.count(extent[0], extent[1]) >= splitNum) {format = 'timeMinute';} else {format = 'timeSecond';}format = correctResult(format, defaultFormat);return format;/*** 判斷出的時間格式,可能不滿足展示要求,* 需要重新進(jìn)行修正* @param {String} format: 判斷出的時間格式* @param {String} defaultFormat: 初始化的時間格式* @return {String} format: 修正后的時間格式*/function correctResult(format, defaultFormat) {if (defaultFormat == 'timeDay') {if (!/timeYear|timeMonth|timeDay/.test(format)) {format = 'timeDay';}} else if (defaultFormat == 'timeMonth') {if (!/timeYear|timeMonth/.test(format)) {format = 'timeMonth';}} else if (defaultFormat == 'timeSecond') {if (!/timeHour|timeMinute|timeSecond/.test(format)) {format = 'timeSecond';}}return format;}}};/*** 得到時間格式對應(yīng)的時間類型* @param {String} timeFormat: 時間格式* @return {String} type: 時間類型:year、month、day、second;*/helper.getTimeType = function(timeFormat) {var type = null;if (['month', 'year', 'day', 'second'].indexOf(timeFormat) > -1) {type = timeFormat;} else if (timeFormat == 'hh:mm:ss' || timeFormat == 'yyyy-MM-dd hh:mm:ss' || timeFormat == 'yyyy/MM/dd hh:mm:ss') {type = 'second';} else if (timeFormat == 'yyyy') {type = 'year';} else if (timeFormat == 'yyyy/MM' || timeFormat == 'yyyyMM' || timeFormat == 'yyyy-MM') {type = 'month';} else if (/(yyyy\-MM\-dd)|(yyyy\/MM\/dd)|(dd\/MM\/yyyy)|(yyyyMMdd)/i.test(timeFormat)) {type = 'day';} else {type = 'second';}return type;};helper.intervalScaleGetTicks = function (extent, niceTickExtent, params) {var ticks = [], timeIntervalPro;var splitNum = params && params.splitNum || 5;var mulDimension = params && params.mulDimension;var timeFormat = params && params.timeFormat;var interval = params.interval;var intervalPrecision = params.intervalPrecision;var type = params.type;// If interval is 0, return [];if (!interval) {return ticks;}splitNum == 1 && (splitNum += 2) || splitNum == 2 && (splitNum += 1);var name = extent[0] + '@#' + extent[1] + '&' + splitNum;if (this.cache[name]) {return this.cache[name];}//沈才良添加 修復(fù)時間處于年和月的顯示錯誤if (type == 'time' && params) { timeFormat = this.getTimeType(timeFormat);if (['year', 'month', 'day', 'second'].indexOf(timeFormat) > -1) {ticks = this.processTimeTicks({extent: extent, niceTickExtent: niceTickExtent, splitNum: splitNum, defaultFormat: 'time' + timeFormat.slice(0, 1).toUpperCase() + timeFormat.slice(1), onlyNum: params.onlyNum});return ticks;}}// Consider this case: using dataZoom toolbox, zoom and zoom.var safeLimit = 10000;if (extent[0] < niceTickExtent[0]) {ticks.push(extent[0]);}var tick = niceTickExtent[0];while (tick <= niceTickExtent[1]) {ticks.push(tick);// Avoid rounding errortick = roundNumber(tick + interval, intervalPrecision);if (tick === ticks[ticks.length - 1]) {// Consider out of safe float point, e.g.,// -3711126.9907707 + 2e-10 === -3711126.9907707break;}if (ticks.length > safeLimit) {return [];}}// Consider this case: the last item of ticks is smaller// than niceTickExtent[1] and niceTickExtent[1] === extent[1].if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {ticks.push(extent[1]);} } return ticks; };(5)Echarts的年時間軸option配置項(xiàng),主要是設(shè)置兩個參數(shù)”timeFormat”、 “tickMax”。”timeFormat”表示時間軸的格式,可以為”yyyy”、“yyyy-MM”、“yyyy-MM-dd”“hh:mm:ss”等,tickMax則表示是否啟用最大刻度個數(shù),blooean類型:true表示啟用。
var option ={"color":["#4cc5f4","#fa5879","#f8e402", ],"tooltip":{"trigger": "item"},"legend":{"show":false,"data":["2013-01","2013-07","2013-09","2013-11","2013-03","2013-05","2013-02","2013-04","2013-06","2013-08","2013-10","2013-12"]},"calculable":true,"xAxis":[{"type":"time", "timeFormat": 'yyyy', "rotate":45,"tickMax": true,min: 'dataMin',max: 'dataMax',"axisLabel":{"tooltip":{"show":true },formatter: function (params) {return new Date(params).Format('yyyy');}},"silent":false,"triggerEvent":true,"selectEvent":true}],"yAxis":[{"type":"value","key":"huan_bi","field":"huan_bi","rotate":0,"boundaryGap":null,"scale":false,"axisLabel":{"margin":10,"tooltip":{"show":true}},"silent":false,"triggerEvent":true,"selectEvent":true,"show":true,"splitLine":{"show":false},"axisTick":{"secondTick":{"show":false,"length":3},"length":6}}],"series":[{"name":"huan_bi","data":[["1998",0.11299999999999999],["1999",0.11299999999999999],["2000",0.12],["2001",0.135],["2003",0.149]],"selectEvent":true,"key":"huan_bi","type":"bar",barWidth:'20%',"symbol":"circle","showAllSymbol":true,"label":{"normal":{"show":false,"textStyle":{"color":"#000"},"formatter":"","position":"top"}}}],"backgroundColor":"#fff"};詳細(xì)源碼:http://download.csdn.net/download/mulumeng981/9977121
寫作水平有限,敬請諒解。
謝謝。
總結(jié)
以上是生活随笔為你收集整理的Echarts时间坐标轴刻度的改进和优化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 商家自建流量池:10种微信引流的方法,值
- 下一篇: RED5与tomcat整合