series-label.src.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /**
  2. * @license Highcharts JS v5.0.6 (2016-12-07)
  3. *
  4. * (c) 2009-2016 Torstein Honsi
  5. *
  6. * License: www.highcharts.com/license
  7. */
  8. (function(factory) {
  9. if (typeof module === 'object' && module.exports) {
  10. module.exports = factory;
  11. } else {
  12. factory(Highcharts);
  13. }
  14. }(function(Highcharts) {
  15. (function(H) {
  16. /**
  17. * (c) 2009-2016 Torstein Honsi
  18. *
  19. * License: www.highcharts.com/license
  20. */
  21. /**
  22. * EXPERIMENTAL Highcharts module to place labels next to a series in a natural position.
  23. *
  24. * TODO:
  25. * - add column support (box collision detection, boxesToAvoid logic)
  26. * - other series types, area etc.
  27. * - avoid data labels, when data labels above, show series label below.
  28. * - add more options (connector, format, formatter)
  29. *
  30. * http://jsfiddle.net/highcharts/L2u9rpwr/
  31. * http://jsfiddle.net/highcharts/y5A37/
  32. * http://jsfiddle.net/highcharts/264Nm/
  33. * http://jsfiddle.net/highcharts/y5A37/
  34. */
  35. 'use strict';
  36. var labelDistance = 3,
  37. wrap = H.wrap,
  38. each = H.each,
  39. extend = H.extend,
  40. isNumber = H.isNumber,
  41. Series = H.Series,
  42. SVGRenderer = H.SVGRenderer,
  43. Chart = H.Chart;
  44. H.setOptions({
  45. plotOptions: {
  46. series: {
  47. label: {
  48. enabled: true,
  49. // Allow labels to be placed distant to the graph if necessary, and
  50. // draw a connector line to the graph
  51. connectorAllowed: true,
  52. connectorNeighbourDistance: 24, // If the label is closer than this to a neighbour graph, draw a connector
  53. styles: {
  54. fontWeight: 'bold'
  55. }
  56. // boxesToAvoid: []
  57. }
  58. }
  59. }
  60. });
  61. /**
  62. * Counter-clockwise, part of the fast line intersection logic
  63. */
  64. function ccw(x1, y1, x2, y2, x3, y3) {
  65. var cw = ((y3 - y1) * (x2 - x1)) - ((y2 - y1) * (x3 - x1));
  66. return cw > 0 ? true : cw < 0 ? false : true;
  67. }
  68. /**
  69. * Detect if two lines intersect
  70. */
  71. function intersectLine(x1, y1, x2, y2, x3, y3, x4, y4) {
  72. return ccw(x1, y1, x3, y3, x4, y4) !== ccw(x2, y2, x3, y3, x4, y4) &&
  73. ccw(x1, y1, x2, y2, x3, y3) !== ccw(x1, y1, x2, y2, x4, y4);
  74. }
  75. /**
  76. * Detect if a box intersects with a line
  77. */
  78. function boxIntersectLine(x, y, w, h, x1, y1, x2, y2) {
  79. return (
  80. intersectLine(x, y, x + w, y, x1, y1, x2, y2) || // top of label
  81. intersectLine(x + w, y, x + w, y + h, x1, y1, x2, y2) || // right of label
  82. intersectLine(x, y + h, x + w, y + h, x1, y1, x2, y2) || // bottom of label
  83. intersectLine(x, y, x, y + h, x1, y1, x2, y2) // left of label
  84. );
  85. }
  86. /**
  87. * General symbol definition for labels with connector
  88. */
  89. SVGRenderer.prototype.symbols.connector = function(x, y, w, h, options) {
  90. var anchorX = options && options.anchorX,
  91. anchorY = options && options.anchorY,
  92. path,
  93. yOffset,
  94. lateral = w / 2;
  95. if (isNumber(anchorX) && isNumber(anchorY)) {
  96. path = ['M', anchorX, anchorY];
  97. // Prefer 45 deg connectors
  98. yOffset = y - anchorY;
  99. if (yOffset < 0) {
  100. yOffset = -h - yOffset;
  101. }
  102. if (yOffset < w) {
  103. lateral = anchorX < x + (w / 2) ? yOffset : w - yOffset;
  104. }
  105. // Anchor below label
  106. if (anchorY > y + h) {
  107. path.push('L', x + lateral, y + h);
  108. // Anchor above label
  109. } else if (anchorY < y) {
  110. path.push('L', x + lateral, y);
  111. // Anchor left of label
  112. } else if (anchorX < x) {
  113. path.push('L', x, y + h / 2);
  114. // Anchor right of label
  115. } else if (anchorX > x + w) {
  116. path.push('L', x + w, y + h / 2);
  117. }
  118. }
  119. return path || [];
  120. };
  121. /**
  122. * Points to avoid. In addition to actual data points, the label should avoid
  123. * interpolated positions.
  124. */
  125. Series.prototype.getPointsOnGraph = function() {
  126. var distance = 16,
  127. points = this.points,
  128. point,
  129. last,
  130. interpolated = [],
  131. i,
  132. deltaX,
  133. deltaY,
  134. delta,
  135. len,
  136. n,
  137. j,
  138. d,
  139. graph = this.graph || this.area,
  140. node = graph.element,
  141. inverted = this.chart.inverted,
  142. paneLeft = inverted ? this.yAxis.pos : this.xAxis.pos,
  143. paneTop = inverted ? this.xAxis.pos : this.yAxis.pos;
  144. // For splines, get the point at length (possible caveat: peaks are not correctly detected)
  145. if (this.getPointSpline && node.getPointAtLength) {
  146. // If it is animating towards a path definition, use that briefly, and reset
  147. if (graph.toD) {
  148. d = graph.attr('d');
  149. graph.attr({
  150. d: graph.toD
  151. });
  152. }
  153. len = node.getTotalLength();
  154. for (i = 0; i < len; i += distance) {
  155. point = node.getPointAtLength(i);
  156. interpolated.push({
  157. chartX: paneLeft + point.x,
  158. chartY: paneTop + point.y,
  159. plotX: point.x,
  160. plotY: point.y
  161. });
  162. }
  163. if (d) {
  164. graph.attr({
  165. d: d
  166. });
  167. }
  168. // Last point
  169. point = points[points.length - 1];
  170. point.chartX = paneLeft + point.plotX;
  171. point.chartY = paneTop + point.plotY;
  172. interpolated.push(point);
  173. // Interpolate
  174. } else {
  175. len = points.length;
  176. for (i = 0; i < len; i += 1) {
  177. point = points[i];
  178. last = points[i - 1];
  179. // Absolute coordinates so we can compare different panes
  180. point.chartX = paneLeft + point.plotX;
  181. point.chartY = paneTop + point.plotY;
  182. // Add interpolated points
  183. if (i > 0) {
  184. deltaX = Math.abs(point.chartX - last.chartX);
  185. deltaY = Math.abs(point.chartY - last.chartY);
  186. delta = Math.max(deltaX, deltaY);
  187. if (delta > distance) {
  188. n = Math.ceil(delta / distance);
  189. for (j = 1; j < n; j += 1) {
  190. interpolated.push({
  191. chartX: last.chartX + (point.chartX - last.chartX) * (j / n),
  192. chartY: last.chartY + (point.chartY - last.chartY) * (j / n),
  193. plotX: last.plotX + (point.plotX - last.plotX) * (j / n),
  194. plotY: last.plotY + (point.plotY - last.plotY) * (j / n)
  195. });
  196. }
  197. }
  198. }
  199. // Add the real point in order to find positive and negative peaks
  200. if (isNumber(point.plotY)) {
  201. interpolated.push(point);
  202. }
  203. }
  204. }
  205. return interpolated;
  206. };
  207. /**
  208. * Check whether a proposed label position is clear of other elements
  209. */
  210. Series.prototype.checkClearPoint = function(x, y, bBox, checkDistance) {
  211. var distToOthersSquared = Number.MAX_VALUE, // distance to other graphs
  212. distToPointSquared = Number.MAX_VALUE,
  213. dist,
  214. connectorPoint,
  215. connectorEnabled = this.options.label.connectorAllowed,
  216. chart = this.chart,
  217. series,
  218. points,
  219. leastDistance = 16,
  220. withinRange,
  221. i,
  222. j;
  223. function intersectRect(r1, r2) {
  224. return !(r2.left > r1.right ||
  225. r2.right < r1.left ||
  226. r2.top > r1.bottom ||
  227. r2.bottom < r1.top);
  228. }
  229. /**
  230. * Get the weight in order to determine the ideal position. Larger distance to
  231. * other series gives more weight. Smaller distance to the actual point (connector points only)
  232. * gives more weight.
  233. */
  234. function getWeight(distToOthersSquared, distToPointSquared) {
  235. return distToOthersSquared - distToPointSquared;
  236. }
  237. // First check for collision with existing labels
  238. for (i = 0; i < chart.boxesToAvoid.length; i += 1) {
  239. if (intersectRect(chart.boxesToAvoid[i], {
  240. left: x,
  241. right: x + bBox.width,
  242. top: y,
  243. bottom: y + bBox.height
  244. })) {
  245. return false;
  246. }
  247. }
  248. // For each position, check if the lines around the label intersect with any of the
  249. // graphs
  250. for (i = 0; i < chart.series.length; i += 1) {
  251. series = chart.series[i];
  252. points = series.interpolatedPoints;
  253. if (series.visible && points) {
  254. for (j = 1; j < points.length; j += 1) {
  255. // If any of the box sides intersect with the line, return
  256. if (boxIntersectLine(
  257. x,
  258. y,
  259. bBox.width,
  260. bBox.height,
  261. points[j - 1].chartX,
  262. points[j - 1].chartY,
  263. points[j].chartX,
  264. points[j].chartY
  265. )) {
  266. return false;
  267. }
  268. // But if it is too far away (a padded box doesn't intersect), also return
  269. if (this === series && !withinRange && checkDistance) {
  270. withinRange = boxIntersectLine(
  271. x - leastDistance,
  272. y - leastDistance,
  273. bBox.width + 2 * leastDistance,
  274. bBox.height + 2 * leastDistance,
  275. points[j - 1].chartX,
  276. points[j - 1].chartY,
  277. points[j].chartX,
  278. points[j].chartY
  279. );
  280. }
  281. // Find the squared distance from the center of the label
  282. if (this !== series) {
  283. distToOthersSquared = Math.min(
  284. distToOthersSquared,
  285. Math.pow(x + bBox.width / 2 - points[j].chartX, 2) + Math.pow(y + bBox.height / 2 - points[j].chartY, 2),
  286. Math.pow(x - points[j].chartX, 2) + Math.pow(y - points[j].chartY, 2),
  287. Math.pow(x + bBox.width - points[j].chartX, 2) + Math.pow(y - points[j].chartY, 2),
  288. Math.pow(x + bBox.width - points[j].chartX, 2) + Math.pow(y + bBox.height - points[j].chartY, 2),
  289. Math.pow(x - points[j].chartX, 2) + Math.pow(y + bBox.height - points[j].chartY, 2)
  290. );
  291. }
  292. }
  293. // Do we need a connector?
  294. if (connectorEnabled && this === series && ((checkDistance && !withinRange) ||
  295. distToOthersSquared < Math.pow(this.options.label.connectorNeighbourDistance, 2))) {
  296. for (j = 1; j < points.length; j += 1) {
  297. dist = Math.min(
  298. Math.pow(x + bBox.width / 2 - points[j].chartX, 2) + Math.pow(y + bBox.height / 2 - points[j].chartY, 2),
  299. Math.pow(x - points[j].chartX, 2) + Math.pow(y - points[j].chartY, 2),
  300. Math.pow(x + bBox.width - points[j].chartX, 2) + Math.pow(y - points[j].chartY, 2),
  301. Math.pow(x + bBox.width - points[j].chartX, 2) + Math.pow(y + bBox.height - points[j].chartY, 2),
  302. Math.pow(x - points[j].chartX, 2) + Math.pow(y + bBox.height - points[j].chartY, 2)
  303. );
  304. if (dist < distToPointSquared) {
  305. distToPointSquared = dist;
  306. connectorPoint = points[j];
  307. }
  308. }
  309. withinRange = true;
  310. }
  311. }
  312. }
  313. return !checkDistance || withinRange ? {
  314. x: x,
  315. y: y,
  316. weight: getWeight(distToOthersSquared, connectorPoint ? distToPointSquared : 0),
  317. connectorPoint: connectorPoint
  318. } : false;
  319. };
  320. /**
  321. * The main initiator method that runs on chart level after initiation and redraw. It runs in
  322. * a timeout to prevent locking, and loops over all series, taking all series and labels into
  323. * account when placing the labels.
  324. */
  325. Chart.prototype.drawSeriesLabels = function() {
  326. var chart = this,
  327. labelSeries = this.labelSeries;
  328. chart.boxesToAvoid = [];
  329. // Build the interpolated points
  330. each(labelSeries, function(series) {
  331. series.interpolatedPoints = series.getPointsOnGraph();
  332. each(series.options.label.boxesToAvoid || [], function(box) {
  333. chart.boxesToAvoid.push(box);
  334. });
  335. });
  336. each(chart.series, function(series) {
  337. var bBox,
  338. x,
  339. y,
  340. results = [],
  341. clearPoint,
  342. i,
  343. best,
  344. inverted = chart.inverted,
  345. paneLeft = inverted ? series.yAxis.pos : series.xAxis.pos,
  346. paneTop = inverted ? series.xAxis.pos : series.yAxis.pos,
  347. paneWidth = chart.inverted ? series.yAxis.len : series.xAxis.len,
  348. paneHeight = chart.inverted ? series.xAxis.len : series.yAxis.len,
  349. points = series.interpolatedPoints,
  350. label = series.labelBySeries;
  351. function insidePane(x, y, bBox) {
  352. return x > paneLeft && x <= paneLeft + paneWidth - bBox.width &&
  353. y >= paneTop && y <= paneTop + paneHeight - bBox.height;
  354. }
  355. if (series.visible && points) {
  356. if (!label) {
  357. series.labelBySeries = label = chart.renderer
  358. .label(series.name, 0, -9999, 'connector')
  359. .css(extend({
  360. color: series.color
  361. }, series.options.label.styles))
  362. .attr({
  363. padding: 0,
  364. opacity: 0,
  365. stroke: series.color,
  366. 'stroke-width': 1
  367. })
  368. .add(series.group)
  369. .animate({
  370. opacity: 1
  371. }, {
  372. duration: 200
  373. });
  374. }
  375. bBox = label.getBBox();
  376. bBox.width = Math.round(bBox.width);
  377. // Ideal positions are centered above or below a point on right side
  378. // of chart
  379. for (i = points.length - 1; i > 0; i -= 1) {
  380. // Right - up
  381. x = points[i].chartX + labelDistance;
  382. y = points[i].chartY - bBox.height - labelDistance;
  383. if (insidePane(x, y, bBox)) {
  384. best = series.checkClearPoint(
  385. x,
  386. y,
  387. bBox
  388. );
  389. }
  390. if (best) {
  391. results.push(best);
  392. }
  393. // Right - down
  394. x = points[i].chartX + labelDistance;
  395. y = points[i].chartY + labelDistance;
  396. if (insidePane(x, y, bBox)) {
  397. best = series.checkClearPoint(
  398. x,
  399. y,
  400. bBox
  401. );
  402. }
  403. if (best) {
  404. results.push(best);
  405. }
  406. // Left - down
  407. x = points[i].chartX - bBox.width - labelDistance;
  408. y = points[i].chartY + labelDistance;
  409. if (insidePane(x, y, bBox)) {
  410. best = series.checkClearPoint(
  411. x,
  412. y,
  413. bBox
  414. );
  415. }
  416. if (best) {
  417. results.push(best);
  418. }
  419. // Left - up
  420. x = points[i].chartX - bBox.width - labelDistance;
  421. y = points[i].chartY - bBox.height - labelDistance;
  422. if (insidePane(x, y, bBox)) {
  423. best = series.checkClearPoint(
  424. x,
  425. y,
  426. bBox
  427. );
  428. }
  429. if (best) {
  430. results.push(best);
  431. }
  432. }
  433. // Brute force, try all positions on the chart in a 16x16 grid
  434. if (!results.length) {
  435. for (x = paneLeft + paneWidth - bBox.width; x >= paneLeft; x -= 16) {
  436. for (y = paneTop; y < paneTop + paneHeight - bBox.height; y += 16) {
  437. clearPoint = series.checkClearPoint(x, y, bBox, true);
  438. if (clearPoint) {
  439. results.push(clearPoint);
  440. }
  441. }
  442. }
  443. }
  444. if (results.length) {
  445. results.sort(function(a, b) {
  446. return b.weight - a.weight;
  447. });
  448. best = results[0];
  449. chart.boxesToAvoid.push({
  450. left: best.x,
  451. right: best.x + bBox.width,
  452. top: best.y,
  453. bottom: best.y + bBox.height
  454. });
  455. // Move it if needed
  456. if (Math.round(best.x) !== Math.round(label.x) ||
  457. Math.round(best.y) !== Math.round(label.y)) {
  458. series.labelBySeries
  459. .attr({
  460. opacity: 0,
  461. x: best.x - paneLeft,
  462. y: best.y - paneTop,
  463. anchorX: best.connectorPoint && best.connectorPoint.plotX,
  464. anchorY: best.connectorPoint && best.connectorPoint.plotY
  465. })
  466. .animate({
  467. opacity: 1
  468. });
  469. // Record closest point to stick to for sync redraw
  470. series.options.kdNow = true;
  471. series.buildKDTree();
  472. var closest = series.searchPoint({
  473. chartX: best.x,
  474. chartY: best.y
  475. }, true);
  476. label.closest = [
  477. closest,
  478. best.x - paneLeft - closest.plotX,
  479. best.y - paneTop - closest.plotY
  480. ];
  481. }
  482. } else if (label) {
  483. series.labelBySeries = label.destroy();
  484. }
  485. }
  486. });
  487. };
  488. /**
  489. * Prepare drawing series labels
  490. */
  491. function drawLabels(proceed) {
  492. var chart = this,
  493. delay = Math.max(
  494. H.animObject(chart.renderer.globalAnimation).duration,
  495. 250
  496. ),
  497. initial = !chart.hasRendered;
  498. proceed.apply(chart, [].slice.call(arguments, 1));
  499. chart.labelSeries = [];
  500. clearTimeout(chart.seriesLabelTimer);
  501. // Which series should have labels
  502. each(chart.series, function(series) {
  503. var options = series.options.label,
  504. label = series.labelBySeries,
  505. closest = label && label.closest;
  506. if (options.enabled && series.visible && (series.graph || series.area)) {
  507. chart.labelSeries.push(series);
  508. // The labels are processing heavy, wait until the animation is done
  509. if (initial) {
  510. delay = Math.max(
  511. delay,
  512. H.animObject(series.options.animation).duration
  513. );
  514. }
  515. // Keep the position updated to the axis while redrawing
  516. if (closest) {
  517. if (closest[0].plotX !== undefined) {
  518. label.animate({
  519. x: closest[0].plotX + closest[1],
  520. y: closest[0].plotY + closest[2]
  521. });
  522. } else {
  523. label.attr({
  524. opacity: 0
  525. });
  526. }
  527. }
  528. }
  529. });
  530. chart.seriesLabelTimer = setTimeout(function() {
  531. chart.drawSeriesLabels();
  532. }, delay);
  533. }
  534. wrap(Chart.prototype, 'render', drawLabels);
  535. wrap(Chart.prototype, 'redraw', drawLabels);
  536. }(Highcharts));
  537. }));