axisHelper.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. var _config = require("../config");
  20. var __DEV__ = _config.__DEV__;
  21. var zrUtil = require("zrender/lib/core/util");
  22. var OrdinalScale = require("../scale/Ordinal");
  23. var IntervalScale = require("../scale/Interval");
  24. var Scale = require("../scale/Scale");
  25. var numberUtil = require("../util/number");
  26. var _barGrid = require("../layout/barGrid");
  27. var prepareLayoutBarSeries = _barGrid.prepareLayoutBarSeries;
  28. var makeColumnLayout = _barGrid.makeColumnLayout;
  29. var retrieveColumnLayout = _barGrid.retrieveColumnLayout;
  30. var BoundingRect = require("zrender/lib/core/BoundingRect");
  31. require("../scale/Time");
  32. require("../scale/Log");
  33. /*
  34. * Licensed to the Apache Software Foundation (ASF) under one
  35. * or more contributor license agreements. See the NOTICE file
  36. * distributed with this work for additional information
  37. * regarding copyright ownership. The ASF licenses this file
  38. * to you under the Apache License, Version 2.0 (the
  39. * "License"); you may not use this file except in compliance
  40. * with the License. You may obtain a copy of the License at
  41. *
  42. * http://www.apache.org/licenses/LICENSE-2.0
  43. *
  44. * Unless required by applicable law or agreed to in writing,
  45. * software distributed under the License is distributed on an
  46. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47. * KIND, either express or implied. See the License for the
  48. * specific language governing permissions and limitations
  49. * under the License.
  50. */
  51. /**
  52. * Get axis scale extent before niced.
  53. * Item of returned array can only be number (including Infinity and NaN).
  54. */
  55. function getScaleExtent(scale, model) {
  56. var scaleType = scale.type;
  57. var min = model.getMin();
  58. var max = model.getMax();
  59. var fixMin = min != null;
  60. var fixMax = max != null;
  61. var originalExtent = scale.getExtent();
  62. var axisDataLen;
  63. var boundaryGap;
  64. var span;
  65. if (scaleType === 'ordinal') {
  66. axisDataLen = model.getCategories().length;
  67. } else {
  68. boundaryGap = model.get('boundaryGap');
  69. if (!zrUtil.isArray(boundaryGap)) {
  70. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  71. }
  72. if (typeof boundaryGap[0] === 'boolean') {
  73. boundaryGap = [0, 0];
  74. }
  75. boundaryGap[0] = numberUtil.parsePercent(boundaryGap[0], 1);
  76. boundaryGap[1] = numberUtil.parsePercent(boundaryGap[1], 1);
  77. span = originalExtent[1] - originalExtent[0] || Math.abs(originalExtent[0]);
  78. } // Notice: When min/max is not set (that is, when there are null/undefined,
  79. // which is the most common case), these cases should be ensured:
  80. // (1) For 'ordinal', show all axis.data.
  81. // (2) For others:
  82. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  83. // disabled).
  84. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  85. // be the result that originalExtent enlarged by boundaryGap.
  86. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  87. // FIXME
  88. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  89. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  90. // that the results processed by boundaryGap are positive/negative?
  91. if (min == null) {
  92. min = scaleType === 'ordinal' ? axisDataLen ? 0 : NaN : originalExtent[0] - boundaryGap[0] * span;
  93. }
  94. if (max == null) {
  95. max = scaleType === 'ordinal' ? axisDataLen ? axisDataLen - 1 : NaN : originalExtent[1] + boundaryGap[1] * span;
  96. }
  97. if (min === 'dataMin') {
  98. min = originalExtent[0];
  99. } else if (typeof min === 'function') {
  100. min = min({
  101. min: originalExtent[0],
  102. max: originalExtent[1]
  103. });
  104. }
  105. if (max === 'dataMax') {
  106. max = originalExtent[1];
  107. } else if (typeof max === 'function') {
  108. max = max({
  109. min: originalExtent[0],
  110. max: originalExtent[1]
  111. });
  112. }
  113. (min == null || !isFinite(min)) && (min = NaN);
  114. (max == null || !isFinite(max)) && (max = NaN);
  115. scale.setBlank(zrUtil.eqNaN(min) || zrUtil.eqNaN(max) || scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length); // Evaluate if axis needs cross zero
  116. if (model.getNeedCrossZero()) {
  117. // Axis is over zero and min is not set
  118. if (min > 0 && max > 0 && !fixMin) {
  119. min = 0;
  120. } // Axis is under zero and max is not set
  121. if (min < 0 && max < 0 && !fixMax) {
  122. max = 0;
  123. }
  124. } // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  125. // is base axis
  126. // FIXME
  127. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  128. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  129. // Should not depend on series type `bar`?
  130. // (3) Fix that might overlap when using dataZoom.
  131. // (4) Consider other chart types using `barGrid`?
  132. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  133. var ecModel = model.ecModel;
  134. if (ecModel && scaleType === 'time'
  135. /*|| scaleType === 'interval' */
  136. ) {
  137. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  138. var isBaseAxisAndHasBarSeries;
  139. zrUtil.each(barSeriesModels, function (seriesModel) {
  140. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  141. });
  142. if (isBaseAxisAndHasBarSeries) {
  143. // Calculate placement of bars on axis
  144. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  145. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  146. min = adjustedScale.min;
  147. max = adjustedScale.max;
  148. }
  149. }
  150. return [min, max];
  151. }
  152. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  153. // Get Axis Length
  154. var axisExtent = model.axis.getExtent();
  155. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  156. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  157. if (barsOnCurrentAxis === undefined) {
  158. return {
  159. min: min,
  160. max: max
  161. };
  162. }
  163. var minOverflow = Infinity;
  164. zrUtil.each(barsOnCurrentAxis, function (item) {
  165. minOverflow = Math.min(item.offset, minOverflow);
  166. });
  167. var maxOverflow = -Infinity;
  168. zrUtil.each(barsOnCurrentAxis, function (item) {
  169. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  170. });
  171. minOverflow = Math.abs(minOverflow);
  172. maxOverflow = Math.abs(maxOverflow);
  173. var totalOverFlow = minOverflow + maxOverflow; // Calulate required buffer based on old range and overflow
  174. var oldRange = max - min;
  175. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  176. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  177. max += overflowBuffer * (maxOverflow / totalOverFlow);
  178. min -= overflowBuffer * (minOverflow / totalOverFlow);
  179. return {
  180. min: min,
  181. max: max
  182. };
  183. }
  184. function niceScaleExtent(scale, model) {
  185. var extent = getScaleExtent(scale, model);
  186. var fixMin = model.getMin() != null;
  187. var fixMax = model.getMax() != null;
  188. var splitNumber = model.get('splitNumber');
  189. if (scale.type === 'log') {
  190. scale.base = model.get('logBase');
  191. }
  192. var scaleType = scale.type;
  193. scale.setExtent(extent[0], extent[1]);
  194. scale.niceExtent({
  195. splitNumber: splitNumber,
  196. fixMin: fixMin,
  197. fixMax: fixMax,
  198. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  199. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  200. }); // If some one specified the min, max. And the default calculated interval
  201. // is not good enough. He can specify the interval. It is often appeared
  202. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  203. // to be 60.
  204. // FIXME
  205. var interval = model.get('interval');
  206. if (interval != null) {
  207. scale.setInterval && scale.setInterval(interval);
  208. }
  209. }
  210. /**
  211. * @param {module:echarts/model/Model} model
  212. * @param {string} [axisType] Default retrieve from model.type
  213. * @return {module:echarts/scale/*}
  214. */
  215. function createScaleByModel(model, axisType) {
  216. axisType = axisType || model.get('type');
  217. if (axisType) {
  218. switch (axisType) {
  219. // Buildin scale
  220. case 'category':
  221. return new OrdinalScale(model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(), [Infinity, -Infinity]);
  222. case 'value':
  223. return new IntervalScale();
  224. // Extended scale, like time and log
  225. default:
  226. return (Scale.getClass(axisType) || IntervalScale).create(model);
  227. }
  228. }
  229. }
  230. /**
  231. * Check if the axis corss 0
  232. */
  233. function ifAxisCrossZero(axis) {
  234. var dataExtent = axis.scale.getExtent();
  235. var min = dataExtent[0];
  236. var max = dataExtent[1];
  237. return !(min > 0 && max > 0 || min < 0 && max < 0);
  238. }
  239. /**
  240. * @param {module:echarts/coord/Axis} axis
  241. * @return {Function} Label formatter function.
  242. * param: {number} tickValue,
  243. * param: {number} idx, the index in all ticks.
  244. * If category axis, this param is not requied.
  245. * return: {string} label string.
  246. */
  247. function makeLabelFormatter(axis) {
  248. var labelFormatter = axis.getLabelModel().get('formatter');
  249. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  250. if (typeof labelFormatter === 'string') {
  251. labelFormatter = function (tpl) {
  252. return function (val) {
  253. // For category axis, get raw value; for numeric axis,
  254. // get foramtted label like '1,333,444'.
  255. val = axis.scale.getLabel(val);
  256. return tpl.replace('{value}', val != null ? val : '');
  257. };
  258. }(labelFormatter); // Consider empty array
  259. return labelFormatter;
  260. } else if (typeof labelFormatter === 'function') {
  261. return function (tickValue, idx) {
  262. // The original intention of `idx` is "the index of the tick in all ticks".
  263. // But the previous implementation of category axis do not consider the
  264. // `axisLabel.interval`, which cause that, for example, the `interval` is
  265. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  266. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  267. // the definition here for back compatibility.
  268. if (categoryTickStart != null) {
  269. idx = tickValue - categoryTickStart;
  270. }
  271. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  272. };
  273. } else {
  274. return function (tick) {
  275. return axis.scale.getLabel(tick);
  276. };
  277. }
  278. }
  279. function getAxisRawValue(axis, value) {
  280. // In category axis with data zoom, tick is not the original
  281. // index of axis.data. So tick should not be exposed to user
  282. // in category axis.
  283. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  284. }
  285. /**
  286. * @param {module:echarts/coord/Axis} axis
  287. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  288. */
  289. function estimateLabelUnionRect(axis) {
  290. var axisModel = axis.model;
  291. var scale = axis.scale;
  292. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  293. return;
  294. }
  295. var isCategory = axis.type === 'category';
  296. var realNumberScaleTicks;
  297. var tickCount;
  298. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  299. if (isCategory) {
  300. tickCount = scale.count();
  301. } else {
  302. realNumberScaleTicks = scale.getTicks();
  303. tickCount = realNumberScaleTicks.length;
  304. }
  305. var axisLabelModel = axis.getLabelModel();
  306. var labelFormatter = makeLabelFormatter(axis);
  307. var rect;
  308. var step = 1; // Simple optimization for large amount of labels
  309. if (tickCount > 40) {
  310. step = Math.ceil(tickCount / 40);
  311. }
  312. for (var i = 0; i < tickCount; i += step) {
  313. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  314. var label = labelFormatter(tickValue);
  315. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  316. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  317. rect ? rect.union(singleRect) : rect = singleRect;
  318. }
  319. return rect;
  320. }
  321. function rotateTextRect(textRect, rotate) {
  322. var rotateRadians = rotate * Math.PI / 180;
  323. var boundingBox = textRect.plain();
  324. var beforeWidth = boundingBox.width;
  325. var beforeHeight = boundingBox.height;
  326. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  327. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  328. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  329. return rotatedRect;
  330. }
  331. /**
  332. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  333. * @return {number|String} Can be null|'auto'|number|function
  334. */
  335. function getOptionCategoryInterval(model) {
  336. var interval = model.get('interval');
  337. return interval == null ? 'auto' : interval;
  338. }
  339. /**
  340. * Set `categoryInterval` as 0 implicitly indicates that
  341. * show all labels reguardless of overlap.
  342. * @param {Object} axis axisModel.axis
  343. * @return {boolean}
  344. */
  345. function shouldShowAllLabels(axis) {
  346. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  347. }
  348. exports.getScaleExtent = getScaleExtent;
  349. exports.niceScaleExtent = niceScaleExtent;
  350. exports.createScaleByModel = createScaleByModel;
  351. exports.ifAxisCrossZero = ifAxisCrossZero;
  352. exports.makeLabelFormatter = makeLabelFormatter;
  353. exports.getAxisRawValue = getAxisRawValue;
  354. exports.estimateLabelUnionRect = estimateLabelUnionRect;
  355. exports.getOptionCategoryInterval = getOptionCategoryInterval;
  356. exports.shouldShowAllLabels = shouldShowAllLabels;