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.

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