vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1293 lines
40 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var util = require('../../util');
  2. var DOMutil = require('../../DOMutil');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var Component = require('./Component');
  6. var DataAxis = require('./DataAxis');
  7. var GraphGroup = require('./GraphGroup');
  8. var Legend = require('./Legend');
  9. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  10. /**
  11. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  12. *
  13. * @param body
  14. * @param options
  15. * @constructor
  16. */
  17. function LineGraph(body, options) {
  18. this.id = util.randomUUID();
  19. this.body = body;
  20. this.defaultOptions = {
  21. yAxisOrientation: 'left',
  22. defaultGroup: 'default',
  23. sort: true,
  24. sampling: true,
  25. graphHeight: '400px',
  26. shaded: {
  27. enabled: false,
  28. orientation: 'bottom' // top, bottom
  29. },
  30. style: 'line', // line, bar
  31. barChart: {
  32. width: 50,
  33. handleOverlap: 'overlap',
  34. align: 'center' // left, center, right
  35. },
  36. catmullRom: {
  37. enabled: true,
  38. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  39. alpha: 0.5
  40. },
  41. drawPoints: {
  42. enabled: true,
  43. size: 6,
  44. style: 'square' // square, circle
  45. },
  46. dataAxis: {
  47. showMinorLabels: true,
  48. showMajorLabels: true,
  49. icons: false,
  50. width: '40px',
  51. visible: true,
  52. customRange: {
  53. left: {min:undefined, max:undefined},
  54. right: {min:undefined, max:undefined}
  55. }
  56. },
  57. legend: {
  58. enabled: false,
  59. icons: true,
  60. left: {
  61. visible: true,
  62. position: 'top-left' // top/bottom - left,right
  63. },
  64. right: {
  65. visible: true,
  66. position: 'top-right' // top/bottom - left,right
  67. }
  68. }
  69. };
  70. // options is shared by this ItemSet and all its items
  71. this.options = util.extend({}, this.defaultOptions);
  72. this.dom = {};
  73. this.props = {};
  74. this.hammer = null;
  75. this.groups = {};
  76. var me = this;
  77. this.itemsData = null; // DataSet
  78. this.groupsData = null; // DataSet
  79. // listeners for the DataSet of the items
  80. this.itemListeners = {
  81. 'add': function (event, params, senderId) {
  82. me._onAdd(params.items);
  83. },
  84. 'update': function (event, params, senderId) {
  85. me._onUpdate(params.items);
  86. },
  87. 'remove': function (event, params, senderId) {
  88. me._onRemove(params.items);
  89. }
  90. };
  91. // listeners for the DataSet of the groups
  92. this.groupListeners = {
  93. 'add': function (event, params, senderId) {
  94. me._onAddGroups(params.items);
  95. },
  96. 'update': function (event, params, senderId) {
  97. me._onUpdateGroups(params.items);
  98. },
  99. 'remove': function (event, params, senderId) {
  100. me._onRemoveGroups(params.items);
  101. }
  102. };
  103. this.items = {}; // object with an Item for every data item
  104. this.selection = []; // list with the ids of all selected nodes
  105. this.lastStart = this.body.range.start;
  106. this.touchParams = {}; // stores properties while dragging
  107. this.svgElements = {};
  108. this.setOptions(options);
  109. this.groupsUsingDefaultStyles = [0];
  110. this.body.emitter.on("rangechange",function() {
  111. if (me.lastStart != 0) {
  112. var offset = me.body.range.start - me.lastStart;
  113. var range = me.body.range.end - me.body.range.start;
  114. if (me.width != 0) {
  115. var rangePerPixelInv = me.width/range;
  116. var xOffset = offset * rangePerPixelInv;
  117. me.svg.style.left = (-me.width - xOffset) + "px";
  118. }
  119. }
  120. });
  121. this.body.emitter.on("rangechanged", function() {
  122. me.lastStart = me.body.range.start;
  123. me.svg.style.left = util.option.asSize(-me.width);
  124. me._updateGraph.apply(me);
  125. });
  126. // create the HTML DOM
  127. this._create();
  128. this.body.emitter.emit("change");
  129. }
  130. LineGraph.prototype = new Component();
  131. /**
  132. * Create the HTML DOM for the ItemSet
  133. */
  134. LineGraph.prototype._create = function(){
  135. var frame = document.createElement('div');
  136. frame.className = 'LineGraph';
  137. this.dom.frame = frame;
  138. // create svg element for graph drawing.
  139. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  140. this.svg.style.position = "relative";
  141. this.svg.style.height = ('' + this.options.graphHeight).replace("px",'') + 'px';
  142. this.svg.style.display = "block";
  143. frame.appendChild(this.svg);
  144. // data axis
  145. this.options.dataAxis.orientation = 'left';
  146. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg);
  147. this.options.dataAxis.orientation = 'right';
  148. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg);
  149. delete this.options.dataAxis.orientation;
  150. // legends
  151. this.legendLeft = new Legend(this.body, this.options.legend, 'left');
  152. this.legendRight = new Legend(this.body, this.options.legend, 'right');
  153. this.show();
  154. };
  155. /**
  156. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  157. * @param options
  158. */
  159. LineGraph.prototype.setOptions = function(options) {
  160. if (options) {
  161. var fields = ['sampling','defaultGroup','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort'];
  162. util.selectiveDeepExtend(fields, this.options, options);
  163. util.mergeOptions(this.options, options,'catmullRom');
  164. util.mergeOptions(this.options, options,'drawPoints');
  165. util.mergeOptions(this.options, options,'shaded');
  166. util.mergeOptions(this.options, options,'legend');
  167. if (options.catmullRom) {
  168. if (typeof options.catmullRom == 'object') {
  169. if (options.catmullRom.parametrization) {
  170. if (options.catmullRom.parametrization == 'uniform') {
  171. this.options.catmullRom.alpha = 0;
  172. }
  173. else if (options.catmullRom.parametrization == 'chordal') {
  174. this.options.catmullRom.alpha = 1.0;
  175. }
  176. else {
  177. this.options.catmullRom.parametrization = 'centripetal';
  178. this.options.catmullRom.alpha = 0.5;
  179. }
  180. }
  181. }
  182. }
  183. if (this.yAxisLeft) {
  184. if (options.dataAxis !== undefined) {
  185. this.yAxisLeft.setOptions(this.options.dataAxis);
  186. this.yAxisRight.setOptions(this.options.dataAxis);
  187. }
  188. }
  189. if (this.legendLeft) {
  190. if (options.legend !== undefined) {
  191. this.legendLeft.setOptions(this.options.legend);
  192. this.legendRight.setOptions(this.options.legend);
  193. }
  194. }
  195. if (this.groups.hasOwnProperty(UNGROUPED)) {
  196. this.groups[UNGROUPED].setOptions(options);
  197. }
  198. }
  199. if (this.dom.frame) {
  200. this._updateGraph();
  201. }
  202. };
  203. /**
  204. * Hide the component from the DOM
  205. */
  206. LineGraph.prototype.hide = function() {
  207. // remove the frame containing the items
  208. if (this.dom.frame.parentNode) {
  209. this.dom.frame.parentNode.removeChild(this.dom.frame);
  210. }
  211. };
  212. /**
  213. * Show the component in the DOM (when not already visible).
  214. * @return {Boolean} changed
  215. */
  216. LineGraph.prototype.show = function() {
  217. // show frame containing the items
  218. if (!this.dom.frame.parentNode) {
  219. this.body.dom.center.appendChild(this.dom.frame);
  220. }
  221. };
  222. /**
  223. * Set items
  224. * @param {vis.DataSet | null} items
  225. */
  226. LineGraph.prototype.setItems = function(items) {
  227. var me = this,
  228. ids,
  229. oldItemsData = this.itemsData;
  230. // replace the dataset
  231. if (!items) {
  232. this.itemsData = null;
  233. }
  234. else if (items instanceof DataSet || items instanceof DataView) {
  235. this.itemsData = items;
  236. }
  237. else {
  238. throw new TypeError('Data must be an instance of DataSet or DataView');
  239. }
  240. if (oldItemsData) {
  241. // unsubscribe from old dataset
  242. util.forEach(this.itemListeners, function (callback, event) {
  243. oldItemsData.off(event, callback);
  244. });
  245. // remove all drawn items
  246. ids = oldItemsData.getIds();
  247. this._onRemove(ids);
  248. }
  249. if (this.itemsData) {
  250. // subscribe to new dataset
  251. var id = this.id;
  252. util.forEach(this.itemListeners, function (callback, event) {
  253. me.itemsData.on(event, callback, id);
  254. });
  255. // add all new items
  256. ids = this.itemsData.getIds();
  257. this._onAdd(ids);
  258. }
  259. this._updateUngrouped();
  260. this._updateGraph();
  261. this.redraw();
  262. };
  263. /**
  264. * Set groups
  265. * @param {vis.DataSet} groups
  266. */
  267. LineGraph.prototype.setGroups = function(groups) {
  268. var me = this,
  269. ids;
  270. // unsubscribe from current dataset
  271. if (this.groupsData) {
  272. util.forEach(this.groupListeners, function (callback, event) {
  273. me.groupsData.unsubscribe(event, callback);
  274. });
  275. // remove all drawn groups
  276. ids = this.groupsData.getIds();
  277. this.groupsData = null;
  278. this._onRemoveGroups(ids); // note: this will cause a redraw
  279. }
  280. // replace the dataset
  281. if (!groups) {
  282. this.groupsData = null;
  283. }
  284. else if (groups instanceof DataSet || groups instanceof DataView) {
  285. this.groupsData = groups;
  286. }
  287. else {
  288. throw new TypeError('Data must be an instance of DataSet or DataView');
  289. }
  290. if (this.groupsData) {
  291. // subscribe to new dataset
  292. var id = this.id;
  293. util.forEach(this.groupListeners, function (callback, event) {
  294. me.groupsData.on(event, callback, id);
  295. });
  296. // draw all ms
  297. ids = this.groupsData.getIds();
  298. this._onAddGroups(ids);
  299. }
  300. this._onUpdate();
  301. };
  302. /**
  303. * Update the datapoints
  304. * @param [ids]
  305. * @private
  306. */
  307. LineGraph.prototype._onUpdate = function(ids) {
  308. this._updateUngrouped();
  309. this._updateAllGroupData();
  310. this._updateGraph();
  311. this.redraw();
  312. };
  313. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  314. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  315. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  316. for (var i = 0; i < groupIds.length; i++) {
  317. var group = this.groupsData.get(groupIds[i]);
  318. this._updateGroup(group, groupIds[i]);
  319. }
  320. this._updateGraph();
  321. this.redraw();
  322. };
  323. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  324. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  325. for (var i = 0; i < groupIds.length; i++) {
  326. if (!this.groups.hasOwnProperty(groupIds[i])) {
  327. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  328. this.yAxisRight.removeGroup(groupIds[i]);
  329. this.legendRight.removeGroup(groupIds[i]);
  330. this.legendRight.redraw();
  331. }
  332. else {
  333. this.yAxisLeft.removeGroup(groupIds[i]);
  334. this.legendLeft.removeGroup(groupIds[i]);
  335. this.legendLeft.redraw();
  336. }
  337. delete this.groups[groupIds[i]];
  338. }
  339. }
  340. this._updateUngrouped();
  341. this._updateGraph();
  342. this.redraw();
  343. };
  344. /**
  345. * update a group object
  346. *
  347. * @param group
  348. * @param groupId
  349. * @private
  350. */
  351. LineGraph.prototype._updateGroup = function (group, groupId) {
  352. if (!this.groups.hasOwnProperty(groupId)) {
  353. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  354. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  355. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  356. this.legendRight.addGroup(groupId, this.groups[groupId]);
  357. }
  358. else {
  359. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  360. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  361. }
  362. }
  363. else {
  364. this.groups[groupId].update(group);
  365. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  366. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  367. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  368. }
  369. else {
  370. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  371. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  372. }
  373. }
  374. this.legendLeft.redraw();
  375. this.legendRight.redraw();
  376. };
  377. LineGraph.prototype._updateAllGroupData = function () {
  378. if (this.itemsData != null) {
  379. var groupsContent = {};
  380. var groupId;
  381. for (groupId in this.groups) {
  382. if (this.groups.hasOwnProperty(groupId)) {
  383. groupsContent[groupId] = [];
  384. }
  385. }
  386. for (var itemId in this.itemsData._data) {
  387. if (this.itemsData._data.hasOwnProperty(itemId)) {
  388. var item = this.itemsData._data[itemId];
  389. item.x = util.convert(item.x,"Date");
  390. groupsContent[item.group].push(item);
  391. }
  392. }
  393. for (groupId in this.groups) {
  394. if (this.groups.hasOwnProperty(groupId)) {
  395. this.groups[groupId].setItems(groupsContent[groupId]);
  396. }
  397. }
  398. }
  399. };
  400. /**
  401. * Create or delete the group holding all ungrouped items. This group is used when
  402. * there are no groups specified. This anonymous group is called 'graph'.
  403. * @protected
  404. */
  405. LineGraph.prototype._updateUngrouped = function() {
  406. if (this.itemsData != null) {
  407. // var t0 = new Date();
  408. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  409. this._updateGroup(group, UNGROUPED);
  410. var ungroupedCounter = 0;
  411. if (this.itemsData) {
  412. for (var itemId in this.itemsData._data) {
  413. if (this.itemsData._data.hasOwnProperty(itemId)) {
  414. var item = this.itemsData._data[itemId];
  415. if (item != undefined) {
  416. if (item.hasOwnProperty('group')) {
  417. if (item.group === undefined) {
  418. item.group = UNGROUPED;
  419. }
  420. }
  421. else {
  422. item.group = UNGROUPED;
  423. }
  424. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  425. }
  426. }
  427. }
  428. }
  429. if (ungroupedCounter == 0) {
  430. delete this.groups[UNGROUPED];
  431. this.legendLeft.removeGroup(UNGROUPED);
  432. this.legendRight.removeGroup(UNGROUPED);
  433. this.yAxisLeft.removeGroup(UNGROUPED);
  434. this.yAxisRight.removeGroup(UNGROUPED);
  435. }
  436. }
  437. else {
  438. delete this.groups[UNGROUPED];
  439. this.legendLeft.removeGroup(UNGROUPED);
  440. this.legendRight.removeGroup(UNGROUPED);
  441. this.yAxisLeft.removeGroup(UNGROUPED);
  442. this.yAxisRight.removeGroup(UNGROUPED);
  443. }
  444. this.legendLeft.redraw();
  445. this.legendRight.redraw();
  446. };
  447. /**
  448. * Redraw the component, mandatory function
  449. * @return {boolean} Returns true if the component is resized
  450. */
  451. LineGraph.prototype.redraw = function() {
  452. var resized = false;
  453. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  454. if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) {
  455. resized = true;
  456. }
  457. // check if this component is resized
  458. resized = this._isResized() || resized;
  459. // check whether zoomed (in that case we need to re-stack everything)
  460. var visibleInterval = this.body.range.end - this.body.range.start;
  461. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  462. this.lastVisibleInterval = visibleInterval;
  463. this.lastWidth = this.width;
  464. // calculate actual size and position
  465. this.width = this.dom.frame.offsetWidth;
  466. // the svg element is three times as big as the width, this allows for fully dragging left and right
  467. // without reloading the graph. the controls for this are bound to events in the constructor
  468. if (resized == true) {
  469. this.svg.style.width = util.option.asSize(3*this.width);
  470. this.svg.style.left = util.option.asSize(-this.width);
  471. }
  472. if (zoomed == true) {
  473. this._updateGraph();
  474. }
  475. this.legendLeft.redraw();
  476. this.legendRight.redraw();
  477. return resized;
  478. };
  479. /**
  480. * Update and redraw the graph.
  481. *
  482. */
  483. LineGraph.prototype._updateGraph = function () {
  484. // reset the svg elements
  485. DOMutil.prepareElements(this.svgElements);
  486. if (this.width != 0 && this.itemsData != null) {
  487. var group, i;
  488. var preprocessedGroupData = {};
  489. var processedGroupData = {};
  490. var groupRanges = {};
  491. var changeCalled = false;
  492. // getting group Ids
  493. var groupIds = [];
  494. for (var groupId in this.groups) {
  495. if (this.groups.hasOwnProperty(groupId)) {
  496. group = this.groups[groupId];
  497. if (group.visible == true) {
  498. groupIds.push(groupId);
  499. }
  500. }
  501. }
  502. if (groupIds.length > 0) {
  503. // this is the range of the SVG canvas
  504. var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width);
  505. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  506. var groupsData = {};
  507. // fill groups data
  508. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  509. // we transform the X coordinates to detect collisions
  510. for (i = 0; i < groupIds.length; i++) {
  511. preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]);
  512. }
  513. // now all needed data has been collected we start the processing.
  514. this._getYRanges(groupIds, preprocessedGroupData, groupRanges);
  515. // update the Y axis first, we use this data to draw at the correct Y points
  516. // changeCalled is required to clean the SVG on a change emit.
  517. changeCalled = this._updateYAxis(groupIds, groupRanges);
  518. if (changeCalled == true) {
  519. DOMutil.cleanupElements(this.svgElements);
  520. this.body.emitter.emit("change");
  521. return;
  522. }
  523. // With the yAxis scaled correctly, use this to get the Y values of the points.
  524. for (i = 0; i < groupIds.length; i++) {
  525. group = this.groups[groupIds[i]];
  526. processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group);
  527. }
  528. // draw the groups
  529. for (i = 0; i < groupIds.length; i++) {
  530. group = this.groups[groupIds[i]];
  531. if (group.options.style == 'line') {
  532. this._drawLineGraph(processedGroupData[groupIds[i]], group);
  533. }
  534. }
  535. this._drawBarGraphs(groupIds, processedGroupData);
  536. }
  537. }
  538. // cleanup unused svg elements
  539. DOMutil.cleanupElements(this.svgElements);
  540. };
  541. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  542. // first select and preprocess the data from the datasets.
  543. // the groups have their preselection of data, we now loop over this data to see
  544. // what data we need to draw. Sorted data is much faster.
  545. // more optimization is possible by doing the sampling before and using the binary search
  546. // to find the end date to determine the increment.
  547. var group, i, j, item;
  548. if (groupIds.length > 0) {
  549. for (i = 0; i < groupIds.length; i++) {
  550. group = this.groups[groupIds[i]];
  551. groupsData[groupIds[i]] = [];
  552. var dataContainer = groupsData[groupIds[i]];
  553. // optimization for sorted data
  554. if (group.options.sort == true) {
  555. var guess = Math.max(0, util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before'));
  556. for (j = guess; j < group.itemsData.length; j++) {
  557. item = group.itemsData[j];
  558. if (item !== undefined) {
  559. if (item.x > maxDate) {
  560. dataContainer.push(item);
  561. break;
  562. }
  563. else {
  564. dataContainer.push(item);
  565. }
  566. }
  567. }
  568. }
  569. else {
  570. for (j = 0; j < group.itemsData.length; j++) {
  571. item = group.itemsData[j];
  572. if (item !== undefined) {
  573. if (item.x > minDate && item.x < maxDate) {
  574. dataContainer.push(item);
  575. }
  576. }
  577. }
  578. }
  579. }
  580. }
  581. this._applySampling(groupIds, groupsData);
  582. };
  583. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  584. var group;
  585. if (groupIds.length > 0) {
  586. for (var i = 0; i < groupIds.length; i++) {
  587. group = this.groups[groupIds[i]];
  588. if (group.options.sampling == true) {
  589. var dataContainer = groupsData[groupIds[i]];
  590. if (dataContainer.length > 0) {
  591. var increment = 1;
  592. var amountOfPoints = dataContainer.length;
  593. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  594. // of width changing of the yAxis.
  595. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  596. var pointsPerPixel = amountOfPoints / xDistance;
  597. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  598. var sampledData = [];
  599. for (var j = 0; j < amountOfPoints; j += increment) {
  600. sampledData.push(dataContainer[j]);
  601. }
  602. groupsData[groupIds[i]] = sampledData;
  603. }
  604. }
  605. }
  606. }
  607. };
  608. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  609. var groupData, group, i,j;
  610. var barCombinedDataLeft = [];
  611. var barCombinedDataRight = [];
  612. var barCombinedData;
  613. if (groupIds.length > 0) {
  614. for (i = 0; i < groupIds.length; i++) {
  615. groupData = groupsData[groupIds[i]];
  616. if (groupData.length > 0) {
  617. group = this.groups[groupIds[i]];
  618. if (group.options.style == 'line' || group.options.barChart.handleOverlap != "stack") {
  619. var yMin = groupData[0].y;
  620. var yMax = groupData[0].y;
  621. for (j = 0; j < groupData.length; j++) {
  622. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  623. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  624. }
  625. groupRanges[groupIds[i]] = {min: yMin, max: yMax, yAxisOrientation: group.options.yAxisOrientation};
  626. }
  627. else if (group.options.style == 'bar') {
  628. if (group.options.yAxisOrientation == 'left') {
  629. barCombinedData = barCombinedDataLeft;
  630. }
  631. else {
  632. barCombinedData = barCombinedDataRight;
  633. }
  634. groupRanges[groupIds[i]] = {min: 0, max: 0, yAxisOrientation: group.options.yAxisOrientation, ignore: true};
  635. // combine data
  636. for (j = 0; j < groupData.length; j++) {
  637. barCombinedData.push({
  638. x: groupData[j].x,
  639. y: groupData[j].y,
  640. groupId: groupIds[i]
  641. });
  642. }
  643. }
  644. }
  645. }
  646. var intersections;
  647. if (barCombinedDataLeft.length > 0) {
  648. // sort by time and by group
  649. barCombinedDataLeft.sort(function (a, b) {
  650. if (a.x == b.x) {
  651. return a.groupId - b.groupId;
  652. } else {
  653. return a.x - b.x;
  654. }
  655. });
  656. intersections = {};
  657. this._getDataIntersections(intersections, barCombinedDataLeft);
  658. groupRanges["__barchartLeft"] = this._getStackedBarYRange(intersections, barCombinedDataLeft);
  659. groupRanges["__barchartLeft"].yAxisOrientation = "left";
  660. groupIds.push("__barchartLeft");
  661. }
  662. if (barCombinedDataRight.length > 0) {
  663. // sort by time and by group
  664. barCombinedDataRight.sort(function (a, b) {
  665. if (a.x == b.x) {
  666. return a.groupId - b.groupId;
  667. } else {
  668. return a.x - b.x;
  669. }
  670. });
  671. intersections = {};
  672. this._getDataIntersections(intersections, barCombinedDataRight);
  673. groupRanges["__barchartRight"] = this._getStackedBarYRange(intersections, barCombinedDataRight);
  674. groupRanges["__barchartRight"].yAxisOrientation = "right";
  675. groupIds.push("__barchartRight");
  676. }
  677. }
  678. };
  679. LineGraph.prototype._getStackedBarYRange = function (intersections, combinedData) {
  680. var key;
  681. var yMin = combinedData[0].y;
  682. var yMax = combinedData[0].y;
  683. for (var i = 0; i < combinedData.length; i++) {
  684. key = combinedData[i].x;
  685. if (intersections[key] === undefined) {
  686. yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin;
  687. yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax;
  688. }
  689. else {
  690. intersections[key].accumulated += combinedData[i].y;
  691. }
  692. }
  693. for (var xpos in intersections) {
  694. if (intersections.hasOwnProperty(xpos)) {
  695. yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin;
  696. yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax;
  697. }
  698. }
  699. return {min: yMin, max: yMax};
  700. };
  701. /**
  702. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  703. * @param {Array} groupIds
  704. * @param {Object} groupRanges
  705. * @private
  706. */
  707. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  708. var changeCalled = false;
  709. var yAxisLeftUsed = false;
  710. var yAxisRightUsed = false;
  711. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  712. // if groups are present
  713. if (groupIds.length > 0) {
  714. for (var i = 0; i < groupIds.length; i++) {
  715. if (groupRanges.hasOwnProperty(groupIds[i])) {
  716. if (groupRanges[groupIds[i]].ignore !== true) {
  717. minVal = groupRanges[groupIds[i]].min;
  718. maxVal = groupRanges[groupIds[i]].max;
  719. if (groupRanges[groupIds[i]].yAxisOrientation == 'left') {
  720. yAxisLeftUsed = true;
  721. minLeft = minLeft > minVal ? minVal : minLeft;
  722. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  723. }
  724. else {
  725. yAxisRightUsed = true;
  726. minRight = minRight > minVal ? minVal : minRight;
  727. maxRight = maxRight < maxVal ? maxVal : maxRight;
  728. }
  729. }
  730. }
  731. }
  732. if (yAxisLeftUsed == true) {
  733. this.yAxisLeft.setRange(minLeft, maxLeft);
  734. }
  735. if (yAxisRightUsed == true) {
  736. this.yAxisRight.setRange(minRight, maxRight);
  737. }
  738. }
  739. changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled;
  740. changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled;
  741. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  742. this.yAxisLeft.drawIcons = true;
  743. this.yAxisRight.drawIcons = true;
  744. }
  745. else {
  746. this.yAxisLeft.drawIcons = false;
  747. this.yAxisRight.drawIcons = false;
  748. }
  749. this.yAxisRight.master = !yAxisLeftUsed;
  750. if (this.yAxisRight.master == false) {
  751. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  752. else {this.yAxisLeft.lineOffset = 0;}
  753. changeCalled = this.yAxisLeft.redraw() || changeCalled;
  754. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  755. changeCalled = this.yAxisRight.redraw() || changeCalled;
  756. }
  757. else {
  758. changeCalled = this.yAxisRight.redraw() || changeCalled;
  759. }
  760. // clean the accumulated lists
  761. if (groupIds.indexOf("__barchartLeft") != -1) {
  762. groupIds.splice(groupIds.indexOf("__barchartLeft"),1);
  763. }
  764. if (groupIds.indexOf("__barchartRight") != -1) {
  765. groupIds.splice(groupIds.indexOf("__barchartRight"),1);
  766. }
  767. return changeCalled;
  768. };
  769. /**
  770. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  771. *
  772. * @param {boolean} axisUsed
  773. * @returns {boolean}
  774. * @private
  775. * @param axis
  776. */
  777. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  778. var changed = false;
  779. if (axisUsed == false) {
  780. if (axis.dom.frame.parentNode) {
  781. axis.hide();
  782. changed = true;
  783. }
  784. }
  785. else {
  786. if (!axis.dom.frame.parentNode) {
  787. axis.show();
  788. changed = true;
  789. }
  790. }
  791. return changed;
  792. };
  793. /**
  794. * draw a bar graph
  795. *
  796. * @param groupIds
  797. * @param processedGroupData
  798. */
  799. LineGraph.prototype._drawBarGraphs = function (groupIds, processedGroupData) {
  800. var combinedData = [];
  801. var intersections = {};
  802. var coreDistance;
  803. var key, drawData;
  804. var group;
  805. var i,j;
  806. var barPoints = 0;
  807. // combine all barchart data
  808. for (i = 0; i < groupIds.length; i++) {
  809. group = this.groups[groupIds[i]];
  810. if (group.options.style == 'bar') {
  811. if (group.visible == true) {
  812. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  813. combinedData.push({
  814. x: processedGroupData[groupIds[i]][j].x,
  815. y: processedGroupData[groupIds[i]][j].y,
  816. groupId: groupIds[i]
  817. });
  818. barPoints += 1;
  819. }
  820. }
  821. }
  822. }
  823. if (barPoints == 0) {return;}
  824. // sort by time and by group
  825. combinedData.sort(function (a, b) {
  826. if (a.x == b.x) {
  827. return a.groupId - b.groupId;
  828. } else {
  829. return a.x - b.x;
  830. }
  831. });
  832. // get intersections
  833. this._getDataIntersections(intersections, combinedData);
  834. // plot barchart
  835. for (i = 0; i < combinedData.length; i++) {
  836. group = this.groups[combinedData[i].groupId];
  837. var minWidth = 0.1 * group.options.barChart.width;
  838. key = combinedData[i].x;
  839. var heightOffset = 0;
  840. if (intersections[key] === undefined) {
  841. if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);}
  842. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));}
  843. drawData = this._getSafeDrawData(coreDistance, group, minWidth);
  844. }
  845. else {
  846. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  847. var prevKey = i - (intersections[key].resolved + 1);
  848. if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);}
  849. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));}
  850. drawData = this._getSafeDrawData(coreDistance, group, minWidth);
  851. intersections[key].resolved += 1;
  852. if (group.options.barChart.handleOverlap == 'stack') {
  853. heightOffset = intersections[key].accumulated;
  854. intersections[key].accumulated += group.zeroPosition - combinedData[i].y;
  855. }
  856. else if (group.options.barChart.handleOverlap == 'sideBySide') {
  857. drawData.width = drawData.width / intersections[key].amount;
  858. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  859. if (group.options.barChart.align == 'left') {drawData.offset -= 0.5*drawData.width;}
  860. else if (group.options.barChart.align == 'right') {drawData.offset += 0.5*drawData.width;}
  861. }
  862. }
  863. DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' bar', this.svgElements, this.svg);
  864. // draw points
  865. if (group.options.drawPoints.enabled == true) {
  866. DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, group, this.svgElements, this.svg);
  867. }
  868. }
  869. };
  870. /**
  871. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  872. * @param intersections
  873. * @param combinedData
  874. * @private
  875. */
  876. LineGraph.prototype._getDataIntersections = function (intersections, combinedData) {
  877. // get intersections
  878. var coreDistance;
  879. for (var i = 0; i < combinedData.length; i++) {
  880. if (i + 1 < combinedData.length) {
  881. coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x);
  882. }
  883. if (i > 0) {
  884. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x));
  885. }
  886. if (coreDistance == 0) {
  887. if (intersections[combinedData[i].x] === undefined) {
  888. intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0};
  889. }
  890. intersections[combinedData[i].x].amount += 1;
  891. }
  892. }
  893. };
  894. /**
  895. * Get the width and offset for bargraphs based on the coredistance between datapoints
  896. *
  897. * @param coreDistance
  898. * @param group
  899. * @param minWidth
  900. * @returns {{width: Number, offset: Number}}
  901. * @private
  902. */
  903. LineGraph.prototype._getSafeDrawData = function (coreDistance, group, minWidth) {
  904. var width, offset;
  905. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  906. width = coreDistance < minWidth ? minWidth : coreDistance;
  907. offset = 0; // recalculate offset with the new width;
  908. if (group.options.barChart.align == 'left') {
  909. offset -= 0.5 * coreDistance;
  910. }
  911. else if (group.options.barChart.align == 'right') {
  912. offset += 0.5 * coreDistance;
  913. }
  914. }
  915. else {
  916. // default settings
  917. width = group.options.barChart.width;
  918. offset = 0;
  919. if (group.options.barChart.align == 'left') {
  920. offset -= 0.5 * group.options.barChart.width;
  921. }
  922. else if (group.options.barChart.align == 'right') {
  923. offset += 0.5 * group.options.barChart.width;
  924. }
  925. }
  926. return {width: width, offset: offset};
  927. };
  928. /**
  929. * draw a line graph
  930. *
  931. * @param dataset
  932. * @param group
  933. */
  934. LineGraph.prototype._drawLineGraph = function (dataset, group) {
  935. if (dataset != null) {
  936. if (dataset.length > 0) {
  937. var path, d;
  938. var svgHeight = Number(this.svg.style.height.replace("px",""));
  939. path = DOMutil.getSVGElement('path', this.svgElements, this.svg);
  940. path.setAttributeNS(null, "class", group.className);
  941. // construct path from dataset
  942. if (group.options.catmullRom.enabled == true) {
  943. d = this._catmullRom(dataset, group);
  944. }
  945. else {
  946. d = this._linear(dataset);
  947. }
  948. // append with points for fill and finalize the path
  949. if (group.options.shaded.enabled == true) {
  950. var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg);
  951. var dFill;
  952. if (group.options.shaded.orientation == 'top') {
  953. dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0;
  954. }
  955. else {
  956. dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight;
  957. }
  958. fillPath.setAttributeNS(null, "class", group.className + " fill");
  959. fillPath.setAttributeNS(null, "d", dFill);
  960. }
  961. // copy properties to path for drawing.
  962. path.setAttributeNS(null, "d", "M" + d);
  963. // draw points
  964. if (group.options.drawPoints.enabled == true) {
  965. this._drawPoints(dataset, group, this.svgElements, this.svg);
  966. }
  967. }
  968. }
  969. };
  970. /**
  971. * draw the data points
  972. *
  973. * @param {Array} dataset
  974. * @param {Object} JSONcontainer
  975. * @param {Object} svg | SVG DOM element
  976. * @param {GraphGroup} group
  977. * @param {Number} [offset]
  978. */
  979. LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) {
  980. if (offset === undefined) {offset = 0;}
  981. for (var i = 0; i < dataset.length; i++) {
  982. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg);
  983. }
  984. };
  985. /**
  986. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  987. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  988. * the yAxis.
  989. *
  990. * @param datapoints
  991. * @returns {Array}
  992. * @private
  993. */
  994. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  995. var extractedData = [];
  996. var xValue, yValue;
  997. var toScreen = this.body.util.toScreen;
  998. for (var i = 0; i < datapoints.length; i++) {
  999. xValue = toScreen(datapoints[i].x) + this.width - 1;
  1000. yValue = datapoints[i].y;
  1001. extractedData.push({x: xValue, y: yValue});
  1002. }
  1003. return extractedData;
  1004. };
  1005. /**
  1006. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  1007. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  1008. * the yAxis.
  1009. *
  1010. * @param datapoints
  1011. * @returns {Array}
  1012. * @private
  1013. */
  1014. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  1015. var extractedData = [];
  1016. var xValue, yValue;
  1017. var toScreen = this.body.util.toScreen;
  1018. var axis = this.yAxisLeft;
  1019. var svgHeight = Number(this.svg.style.height.replace("px",""));
  1020. if (group.options.yAxisOrientation == 'right') {
  1021. axis = this.yAxisRight;
  1022. }
  1023. for (var i = 0; i < datapoints.length; i++) {
  1024. xValue = toScreen(datapoints[i].x) + this.width - 1;
  1025. yValue = Math.round(axis.convertValue(datapoints[i].y));
  1026. extractedData.push({x: xValue, y: yValue});
  1027. }
  1028. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  1029. return extractedData;
  1030. };
  1031. /**
  1032. * This uses an uniform parametrization of the CatmullRom algorithm:
  1033. * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al.
  1034. * @param data
  1035. * @returns {string}
  1036. * @private
  1037. */
  1038. LineGraph.prototype._catmullRomUniform = function(data) {
  1039. // catmull rom
  1040. var p0, p1, p2, p3, bp1, bp2;
  1041. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  1042. var normalization = 1/6;
  1043. var length = data.length;
  1044. for (var i = 0; i < length - 1; i++) {
  1045. p0 = (i == 0) ? data[0] : data[i-1];
  1046. p1 = data[i];
  1047. p2 = data[i+1];
  1048. p3 = (i + 2 < length) ? data[i+2] : p2;
  1049. // Catmull-Rom to Cubic Bezier conversion matrix
  1050. // 0 1 0 0
  1051. // -1/6 1 1/6 0
  1052. // 0 1/6 1 -1/6
  1053. // 0 0 1 0
  1054. // bp0 = { x: p1.x, y: p1.y };
  1055. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  1056. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  1057. // bp0 = { x: p2.x, y: p2.y };
  1058. d += "C" +
  1059. bp1.x + "," +
  1060. bp1.y + " " +
  1061. bp2.x + "," +
  1062. bp2.y + " " +
  1063. p2.x + "," +
  1064. p2.y + " ";
  1065. }
  1066. return d;
  1067. };
  1068. /**
  1069. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  1070. * By default, the centripetal parameterization is used because this gives the nicest results.
  1071. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  1072. *
  1073. * One optimization can be used to reuse distances since this is a sliding window approach.
  1074. * @param data
  1075. * @returns {string}
  1076. * @private
  1077. */
  1078. LineGraph.prototype._catmullRom = function(data, group) {
  1079. var alpha = group.options.catmullRom.alpha;
  1080. if (alpha == 0 || alpha === undefined) {
  1081. return this._catmullRomUniform(data);
  1082. }
  1083. else {
  1084. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  1085. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  1086. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  1087. var length = data.length;
  1088. for (var i = 0; i < length - 1; i++) {
  1089. p0 = (i == 0) ? data[0] : data[i-1];
  1090. p1 = data[i];
  1091. p2 = data[i+1];
  1092. p3 = (i + 2 < length) ? data[i+2] : p2;
  1093. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  1094. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  1095. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  1096. // Catmull-Rom to Cubic Bezier conversion matrix
  1097. //
  1098. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  1099. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  1100. //
  1101. // [ 0 1 0 0 ]
  1102. // [ -d2^2a/N A/N d1^2a/N 0 ]
  1103. // [ 0 d3^2a/M B/M -d2^2a/M ]
  1104. // [ 0 0 1 0 ]
  1105. // [ 0 1 0 0 ]
  1106. // [ -d2pow2a/N A/N d1pow2a/N 0 ]
  1107. // [ 0 d3pow2a/M B/M -d2pow2a/M ]
  1108. // [ 0 0 1 0 ]
  1109. d3powA = Math.pow(d3, alpha);
  1110. d3pow2A = Math.pow(d3,2*alpha);
  1111. d2powA = Math.pow(d2, alpha);
  1112. d2pow2A = Math.pow(d2,2*alpha);
  1113. d1powA = Math.pow(d1, alpha);
  1114. d1pow2A = Math.pow(d1,2*alpha);
  1115. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  1116. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  1117. N = 3*d1powA * (d1powA + d2powA);
  1118. if (N > 0) {N = 1 / N;}
  1119. M = 3*d3powA * (d3powA + d2powA);
  1120. if (M > 0) {M = 1 / M;}
  1121. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  1122. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  1123. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  1124. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  1125. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  1126. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  1127. d += "C" +
  1128. bp1.x + "," +
  1129. bp1.y + " " +
  1130. bp2.x + "," +
  1131. bp2.y + " " +
  1132. p2.x + "," +
  1133. p2.y + " ";
  1134. }
  1135. return d;
  1136. }
  1137. };
  1138. /**
  1139. * this generates the SVG path for a linear drawing between datapoints.
  1140. * @param data
  1141. * @returns {string}
  1142. * @private
  1143. */
  1144. LineGraph.prototype._linear = function(data) {
  1145. // linear
  1146. var d = "";
  1147. for (var i = 0; i < data.length; i++) {
  1148. if (i == 0) {
  1149. d += data[i].x + "," + data[i].y;
  1150. }
  1151. else {
  1152. d += " " + data[i].x + "," + data[i].y;
  1153. }
  1154. }
  1155. return d;
  1156. };
  1157. module.exports = LineGraph;