axisHelper.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. /**
  20. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21. */
  22. /*
  23. * Licensed to the Apache Software Foundation (ASF) under one
  24. * or more contributor license agreements. See the NOTICE file
  25. * distributed with this work for additional information
  26. * regarding copyright ownership. The ASF licenses this file
  27. * to you under the Apache License, Version 2.0 (the
  28. * "License"); you may not use this file except in compliance
  29. * with the License. You may obtain a copy of the License at
  30. *
  31. * http://www.apache.org/licenses/LICENSE-2.0
  32. *
  33. * Unless required by applicable law or agreed to in writing,
  34. * software distributed under the License is distributed on an
  35. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36. * KIND, either express or implied. See the License for the
  37. * specific language governing permissions and limitations
  38. * under the License.
  39. */
  40. import * as zrUtil from 'zrender/lib/core/util.js';
  41. import OrdinalScale from '../scale/Ordinal.js';
  42. import IntervalScale from '../scale/Interval.js';
  43. import Scale from '../scale/Scale.js';
  44. import { prepareLayoutBarSeries, makeColumnLayout, retrieveColumnLayout } from '../layout/barGrid.js';
  45. import BoundingRect from 'zrender/lib/core/BoundingRect.js';
  46. import TimeScale from '../scale/Time.js';
  47. import LogScale from '../scale/Log.js';
  48. import { getStackedDimension } from '../data/helper/dataStackHelper.js';
  49. import { ensureScaleRawExtentInfo } from './scaleRawExtentInfo.js';
  50. /**
  51. * Get axis scale extent before niced.
  52. * Item of returned array can only be number (including Infinity and NaN).
  53. *
  54. * Caution:
  55. * Precondition of calling this method:
  56. * The scale extent has been initialized using series data extent via
  57. * `scale.setExtent` or `scale.unionExtentFromData`;
  58. */
  59. export function getScaleExtent(scale, model) {
  60. var scaleType = scale.type;
  61. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  62. scale.setBlank(rawExtentResult.isBlank);
  63. var min = rawExtentResult.min;
  64. var max = rawExtentResult.max;
  65. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  66. // is base axis
  67. // FIXME
  68. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  69. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  70. // Should not depend on series type `bar`?
  71. // (3) Fix that might overlap when using dataZoom.
  72. // (4) Consider other chart types using `barGrid`?
  73. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  74. var ecModel = model.ecModel;
  75. if (ecModel && scaleType === 'time' /* || scaleType === 'interval' */) {
  76. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  77. var isBaseAxisAndHasBarSeries_1 = false;
  78. zrUtil.each(barSeriesModels, function (seriesModel) {
  79. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  80. });
  81. if (isBaseAxisAndHasBarSeries_1) {
  82. // Calculate placement of bars on axis. TODO should be decoupled
  83. // with barLayout
  84. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  85. // Adjust axis min and max to account for overflow
  86. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  87. min = adjustedScale.min;
  88. max = adjustedScale.max;
  89. }
  90. }
  91. return {
  92. extent: [min, max],
  93. // "fix" means "fixed", the value should not be
  94. // changed in the subsequent steps.
  95. fixMin: rawExtentResult.minFixed,
  96. fixMax: rawExtentResult.maxFixed
  97. };
  98. }
  99. function adjustScaleForOverflow(min, max, model,
  100. // Only support cartesian coord yet.
  101. barWidthAndOffset) {
  102. // Get Axis Length
  103. var axisExtent = model.axis.getExtent();
  104. var axisLength = axisExtent[1] - axisExtent[0];
  105. // Get bars on current base axis and calculate min and max overflow
  106. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  107. if (barsOnCurrentAxis === undefined) {
  108. return {
  109. min: min,
  110. max: max
  111. };
  112. }
  113. var minOverflow = Infinity;
  114. zrUtil.each(barsOnCurrentAxis, function (item) {
  115. minOverflow = Math.min(item.offset, minOverflow);
  116. });
  117. var maxOverflow = -Infinity;
  118. zrUtil.each(barsOnCurrentAxis, function (item) {
  119. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  120. });
  121. minOverflow = Math.abs(minOverflow);
  122. maxOverflow = Math.abs(maxOverflow);
  123. var totalOverFlow = minOverflow + maxOverflow;
  124. // Calculate required buffer based on old range and overflow
  125. var oldRange = max - min;
  126. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  127. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  128. max += overflowBuffer * (maxOverflow / totalOverFlow);
  129. min -= overflowBuffer * (minOverflow / totalOverFlow);
  130. return {
  131. min: min,
  132. max: max
  133. };
  134. }
  135. // Precondition of calling this method:
  136. // The scale extent has been initialized using series data extent via
  137. // `scale.setExtent` or `scale.unionExtentFromData`;
  138. export function niceScaleExtent(scale, inModel) {
  139. var model = inModel;
  140. var extentInfo = getScaleExtent(scale, model);
  141. var extent = extentInfo.extent;
  142. var splitNumber = model.get('splitNumber');
  143. if (scale instanceof LogScale) {
  144. scale.base = model.get('logBase');
  145. }
  146. var scaleType = scale.type;
  147. var interval = model.get('interval');
  148. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  149. scale.setExtent(extent[0], extent[1]);
  150. scale.calcNiceExtent({
  151. splitNumber: splitNumber,
  152. fixMin: extentInfo.fixMin,
  153. fixMax: extentInfo.fixMax,
  154. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  155. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  156. });
  157. // If some one specified the min, max. And the default calculated interval
  158. // is not good enough. He can specify the interval. It is often appeared
  159. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  160. // to be 60.
  161. // FIXME
  162. if (interval != null) {
  163. scale.setInterval && scale.setInterval(interval);
  164. }
  165. }
  166. /**
  167. * @param axisType Default retrieve from model.type
  168. */
  169. export function createScaleByModel(model, axisType) {
  170. axisType = axisType || model.get('type');
  171. if (axisType) {
  172. switch (axisType) {
  173. // Buildin scale
  174. case 'category':
  175. return new OrdinalScale({
  176. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  177. extent: [Infinity, -Infinity]
  178. });
  179. case 'time':
  180. return new TimeScale({
  181. locale: model.ecModel.getLocaleModel(),
  182. useUTC: model.ecModel.get('useUTC')
  183. });
  184. default:
  185. // case 'value'/'interval', 'log', or others.
  186. return new (Scale.getClass(axisType) || IntervalScale)();
  187. }
  188. }
  189. }
  190. /**
  191. * Check if the axis cross 0
  192. */
  193. export function ifAxisCrossZero(axis) {
  194. var dataExtent = axis.scale.getExtent();
  195. var min = dataExtent[0];
  196. var max = dataExtent[1];
  197. return !(min > 0 && max > 0 || min < 0 && max < 0);
  198. }
  199. /**
  200. * @param axis
  201. * @return Label formatter function.
  202. * param: {number} tickValue,
  203. * param: {number} idx, the index in all ticks.
  204. * If category axis, this param is not required.
  205. * return: {string} label string.
  206. */
  207. export function makeLabelFormatter(axis) {
  208. var labelFormatter = axis.getLabelModel().get('formatter');
  209. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  210. if (axis.scale.type === 'time') {
  211. return function (tpl) {
  212. return function (tick, idx) {
  213. return axis.scale.getFormattedLabel(tick, idx, tpl);
  214. };
  215. }(labelFormatter);
  216. } else if (zrUtil.isString(labelFormatter)) {
  217. return function (tpl) {
  218. return function (tick) {
  219. // For category axis, get raw value; for numeric axis,
  220. // get formatted label like '1,333,444'.
  221. var label = axis.scale.getLabel(tick);
  222. var text = tpl.replace('{value}', label != null ? label : '');
  223. return text;
  224. };
  225. }(labelFormatter);
  226. } else if (zrUtil.isFunction(labelFormatter)) {
  227. return function (cb) {
  228. return function (tick, idx) {
  229. // The original intention of `idx` is "the index of the tick in all ticks".
  230. // But the previous implementation of category axis do not consider the
  231. // `axisLabel.interval`, which cause that, for example, the `interval` is
  232. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  233. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  234. // the definition here for back compatibility.
  235. if (categoryTickStart != null) {
  236. idx = tick.value - categoryTickStart;
  237. }
  238. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  239. level: tick.level
  240. } : null);
  241. };
  242. }(labelFormatter);
  243. } else {
  244. return function (tick) {
  245. return axis.scale.getLabel(tick);
  246. };
  247. }
  248. }
  249. export function getAxisRawValue(axis, tick) {
  250. // In category axis with data zoom, tick is not the original
  251. // index of axis.data. So tick should not be exposed to user
  252. // in category axis.
  253. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  254. }
  255. /**
  256. * @param axis
  257. * @return Be null/undefined if no labels.
  258. */
  259. export function estimateLabelUnionRect(axis) {
  260. var axisModel = axis.model;
  261. var scale = axis.scale;
  262. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  263. return;
  264. }
  265. var realNumberScaleTicks;
  266. var tickCount;
  267. var categoryScaleExtent = scale.getExtent();
  268. // Optimize for large category data, avoid call `getTicks()`.
  269. if (scale instanceof OrdinalScale) {
  270. tickCount = scale.count();
  271. } else {
  272. realNumberScaleTicks = scale.getTicks();
  273. tickCount = realNumberScaleTicks.length;
  274. }
  275. var axisLabelModel = axis.getLabelModel();
  276. var labelFormatter = makeLabelFormatter(axis);
  277. var rect;
  278. var step = 1;
  279. // Simple optimization for large amount of labels
  280. if (tickCount > 40) {
  281. step = Math.ceil(tickCount / 40);
  282. }
  283. for (var i = 0; i < tickCount; i += step) {
  284. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  285. value: categoryScaleExtent[0] + i
  286. };
  287. var label = labelFormatter(tick, i);
  288. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  289. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  290. rect ? rect.union(singleRect) : rect = singleRect;
  291. }
  292. return rect;
  293. }
  294. function rotateTextRect(textRect, rotate) {
  295. var rotateRadians = rotate * Math.PI / 180;
  296. var beforeWidth = textRect.width;
  297. var beforeHeight = textRect.height;
  298. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  299. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  300. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  301. return rotatedRect;
  302. }
  303. /**
  304. * @param model axisLabelModel or axisTickModel
  305. * @return {number|String} Can be null|'auto'|number|function
  306. */
  307. export function getOptionCategoryInterval(model) {
  308. var interval = model.get('interval');
  309. return interval == null ? 'auto' : interval;
  310. }
  311. /**
  312. * Set `categoryInterval` as 0 implicitly indicates that
  313. * show all labels regardless of overlap.
  314. * @param {Object} axis axisModel.axis
  315. */
  316. export function shouldShowAllLabels(axis) {
  317. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  318. }
  319. export function getDataDimensionsOnAxis(data, axisDim) {
  320. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  321. var dataDimMap = {};
  322. // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  323. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  324. // there has been stacked result dim?
  325. zrUtil.each(data.mapDimensionsAll(axisDim), function (dataDim) {
  326. // For example, the extent of the original dimension
  327. // is [0.1, 0.5], the extent of the `stackResultDimension`
  328. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  329. // because there is no graphic corresponding to [0.1, 0.5].
  330. // See the case in `test/area-stack.html` `main1`, where area line
  331. // stack needs `yAxis` not start from 0.
  332. dataDimMap[getStackedDimension(data, dataDim)] = true;
  333. });
  334. return zrUtil.keys(dataDimMap);
  335. }
  336. export function unionAxisExtentFromData(dataExtent, data, axisDim) {
  337. if (data) {
  338. zrUtil.each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  339. var seriesExtent = data.getApproximateExtent(dim);
  340. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  341. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  342. });
  343. }
  344. }