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.

1284 lines
39 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
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. LineGraph.prototype._onUpdate = function(ids) {
  303. this._updateUngrouped();
  304. this._updateAllGroupData();
  305. this._updateGraph();
  306. this.redraw();
  307. };
  308. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  309. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  310. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  311. for (var i = 0; i < groupIds.length; i++) {
  312. var group = this.groupsData.get(groupIds[i]);
  313. this._updateGroup(group, groupIds[i]);
  314. }
  315. this._updateGraph();
  316. this.redraw();
  317. };
  318. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  319. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  320. for (var i = 0; i < groupIds.length; i++) {
  321. if (!this.groups.hasOwnProperty(groupIds[i])) {
  322. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  323. this.yAxisRight.removeGroup(groupIds[i]);
  324. this.legendRight.removeGroup(groupIds[i]);
  325. this.legendRight.redraw();
  326. }
  327. else {
  328. this.yAxisLeft.removeGroup(groupIds[i]);
  329. this.legendLeft.removeGroup(groupIds[i]);
  330. this.legendLeft.redraw();
  331. }
  332. delete this.groups[groupIds[i]];
  333. }
  334. }
  335. this._updateUngrouped();
  336. this._updateGraph();
  337. this.redraw();
  338. };
  339. /**
  340. * update a group object
  341. *
  342. * @param group
  343. * @param groupId
  344. * @private
  345. */
  346. LineGraph.prototype._updateGroup = function (group, groupId) {
  347. if (!this.groups.hasOwnProperty(groupId)) {
  348. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  349. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  350. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  351. this.legendRight.addGroup(groupId, this.groups[groupId]);
  352. }
  353. else {
  354. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  355. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  356. }
  357. }
  358. else {
  359. this.groups[groupId].update(group);
  360. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  361. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  362. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  363. }
  364. else {
  365. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  366. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  367. }
  368. }
  369. this.legendLeft.redraw();
  370. this.legendRight.redraw();
  371. };
  372. LineGraph.prototype._updateAllGroupData = function () {
  373. if (this.itemsData != null) {
  374. var groupsContent = {};
  375. for (var groupId in this.groups) {
  376. if (this.groups.hasOwnProperty(groupId)) {
  377. groupsContent[groupId] = [];
  378. }
  379. }
  380. for (var itemId in this.itemsData._data) {
  381. if (this.itemsData._data.hasOwnProperty(itemId)) {
  382. var item = this.itemsData._data[itemId];
  383. item.x = util.convert(item.x,"Date");
  384. groupsContent[item.group].push(item);
  385. }
  386. }
  387. for (var groupId in this.groups) {
  388. if (this.groups.hasOwnProperty(groupId)) {
  389. this.groups[groupId].setItems(groupsContent[groupId]);
  390. }
  391. }
  392. }
  393. };
  394. /**
  395. * Create or delete the group holding all ungrouped items. This group is used when
  396. * there are no groups specified. This anonymous group is called 'graph'.
  397. * @protected
  398. */
  399. LineGraph.prototype._updateUngrouped = function() {
  400. if (this.itemsData != null) {
  401. // var t0 = new Date();
  402. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  403. this._updateGroup(group, UNGROUPED);
  404. var ungroupedCounter = 0;
  405. if (this.itemsData) {
  406. for (var itemId in this.itemsData._data) {
  407. if (this.itemsData._data.hasOwnProperty(itemId)) {
  408. var item = this.itemsData._data[itemId];
  409. if (item != undefined) {
  410. if (item.hasOwnProperty('group')) {
  411. if (item.group === undefined) {
  412. item.group = UNGROUPED;
  413. }
  414. }
  415. else {
  416. item.group = UNGROUPED;
  417. }
  418. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  419. }
  420. }
  421. }
  422. }
  423. // much much slower
  424. // var datapoints = this.itemsData.get({
  425. // filter: function (item) {return item.group === undefined;},
  426. // showInternalIds:true
  427. // });
  428. // if (datapoints.length > 0) {
  429. // var updateQuery = [];
  430. // for (var i = 0; i < datapoints.length; i++) {
  431. // updateQuery.push({id:datapoints[i].id, group: UNGROUPED});
  432. // }
  433. // this.itemsData.update(updateQuery, true);
  434. // }
  435. // var t1 = new Date();
  436. // var pointInUNGROUPED = this.itemsData.get({filter: function (item) {return item.group == UNGROUPED;}});
  437. if (ungroupedCounter == 0) {
  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. // console.log("getting amount ungrouped",new Date() - t1);
  445. // console.log("putting in ungrouped",new Date() - t0);
  446. }
  447. else {
  448. delete this.groups[UNGROUPED];
  449. this.legendLeft.removeGroup(UNGROUPED);
  450. this.legendRight.removeGroup(UNGROUPED);
  451. this.yAxisLeft.removeGroup(UNGROUPED);
  452. this.yAxisRight.removeGroup(UNGROUPED);
  453. }
  454. this.legendLeft.redraw();
  455. this.legendRight.redraw();
  456. };
  457. /**
  458. * Redraw the component, mandatory function
  459. * @return {boolean} Returns true if the component is resized
  460. */
  461. LineGraph.prototype.redraw = function() {
  462. var resized = false;
  463. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  464. if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) {
  465. resized = true;
  466. }
  467. // check if this component is resized
  468. resized = this._isResized() || resized;
  469. // check whether zoomed (in that case we need to re-stack everything)
  470. var visibleInterval = this.body.range.end - this.body.range.start;
  471. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  472. this.lastVisibleInterval = visibleInterval;
  473. this.lastWidth = this.width;
  474. // calculate actual size and position
  475. this.width = this.dom.frame.offsetWidth;
  476. // the svg element is three times as big as the width, this allows for fully dragging left and right
  477. // without reloading the graph. the controls for this are bound to events in the constructor
  478. if (resized == true) {
  479. this.svg.style.width = util.option.asSize(3*this.width);
  480. this.svg.style.left = util.option.asSize(-this.width);
  481. }
  482. if (zoomed == true) {
  483. this._updateGraph();
  484. }
  485. this.legendLeft.redraw();
  486. this.legendRight.redraw();
  487. return resized;
  488. };
  489. /**
  490. * Update and redraw the graph.
  491. *
  492. */
  493. LineGraph.prototype._updateGraph = function () {
  494. // reset the svg elements
  495. DOMutil.prepareElements(this.svgElements);
  496. if (this.width != 0 && this.itemsData != null) {
  497. var group, i;
  498. var preprocessedGroupData = {};
  499. var processedGroupData = {};
  500. var groupRanges = {};
  501. var changeCalled = false;
  502. // getting group Ids
  503. var groupIds = [];
  504. for (var groupId in this.groups) {
  505. if (this.groups.hasOwnProperty(groupId)) {
  506. group = this.groups[groupId];
  507. if (group.visible == true) {
  508. groupIds.push(groupId);
  509. }
  510. }
  511. }
  512. if (groupIds.length > 0) {
  513. // this is the range of the SVG canvas
  514. var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width);
  515. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  516. var groupsData = {};
  517. // fill groups data
  518. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  519. // we transform the X coordinates to detect collisions
  520. for (i = 0; i < groupIds.length; i++) {
  521. preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]);
  522. }
  523. // now all needed data has been collected we start the processing.
  524. this._getYRanges(groupIds, preprocessedGroupData, groupRanges);
  525. // update the Y axis first, we use this data to draw at the correct Y points
  526. // changeCalled is required to clean the SVG on a change emit.
  527. changeCalled = this._updateYAxis(groupIds, groupRanges);
  528. if (changeCalled == true) {
  529. DOMutil.cleanupElements(this.svgElements);
  530. this.body.emitter.emit("change");
  531. return;
  532. }
  533. // With the yAxis scaled correctly, use this to get the Y values of the points.
  534. for (i = 0; i < groupIds.length; i++) {
  535. group = this.groups[groupIds[i]];
  536. processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group);
  537. }
  538. // draw the groups
  539. for (i = 0; i < groupIds.length; i++) {
  540. group = this.groups[groupIds[i]];
  541. if (group.options.style == 'line') {
  542. this._drawLineGraph(processedGroupData[groupIds[i]], group);
  543. }
  544. }
  545. this._drawBarGraphs(groupIds, processedGroupData);
  546. }
  547. }
  548. // cleanup unused svg elements
  549. DOMutil.cleanupElements(this.svgElements);
  550. };
  551. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  552. // first select and preprocess the data from the datasets.
  553. // the groups have their preselection of data, we now loop over this data to see
  554. // what data we need to draw. Sorted data is much faster.
  555. // more optimization is possible by doing the sampling before and using the binary search
  556. // to find the end date to determine the increment.
  557. var group;
  558. if (groupIds.length > 0) {
  559. for (var i = 0; i < groupIds.length; i++) {
  560. group = this.groups[groupIds[i]];
  561. groupsData[groupIds[i]] = [];
  562. var dataContainer = groupsData[groupIds[i]];
  563. // optimization for sorted data
  564. if (group.options.sort == true) {
  565. var guess = Math.max(0, util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before'));
  566. for (var j = guess; j < group.itemsData.length; j++) {
  567. var item = group.itemsData[j];
  568. if (item !== undefined) {
  569. if (item.x > maxDate) {
  570. dataContainer.push(item);
  571. break;
  572. }
  573. else {
  574. dataContainer.push(item);
  575. }
  576. }
  577. }
  578. }
  579. else {
  580. for (var j = 0; j < group.itemsData.length; j++) {
  581. var item = group.itemsData[j];
  582. if (item !== undefined) {
  583. if (item.x > minDate && item.x < maxDate) {
  584. dataContainer.push(item);
  585. }
  586. }
  587. }
  588. }
  589. }
  590. }
  591. this._applySampling(groupIds, groupsData);
  592. };
  593. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  594. var group;
  595. if (groupIds.length > 0) {
  596. for (var i = 0; i < groupIds.length; i++) {
  597. group = this.groups[groupIds[i]];
  598. if (group.options.sampling == true) {
  599. var dataContainer = groupsData[groupIds[i]];
  600. var increment = 1;
  601. var amountOfPoints = dataContainer.length;
  602. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  603. // of width changing of the yAxis.
  604. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  605. var pointsPerPixel = amountOfPoints / xDistance;
  606. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  607. var sampledData = [];
  608. for (var j = 0; j < amountOfPoints; j += increment) {
  609. sampledData.push(dataContainer[j]);
  610. }
  611. groupsData[groupIds[i]] = sampledData;
  612. }
  613. }
  614. }
  615. };
  616. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  617. var groupData, group;
  618. var barCombinedDataLeft = [];
  619. var barCombinedDataRight = [];
  620. var barCombinedData;
  621. if (groupIds.length > 0) {
  622. for (var i = 0; i < groupIds.length; i++) {
  623. groupData = groupsData[groupIds[i]];
  624. group = this.groups[groupIds[i]];
  625. if (group.options.style == 'line' || group.options.barChart.handleOverlap != "stack") {
  626. var yMin = groupData[0].y;
  627. var yMax = groupData[0].y;
  628. for (var j = 0; j < groupData.length; j++) {
  629. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  630. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  631. }
  632. groupRanges[groupIds[i]] = {min: yMin, max: yMax, yAxisOrientation: group.options.yAxisOrientation};
  633. }
  634. else if (group.options.style == 'bar') {
  635. if (group.options.yAxisOrientation == 'left') {
  636. barCombinedData = barCombinedDataLeft;
  637. }
  638. else {
  639. barCombinedData = barCombinedDataRight;
  640. }
  641. groupRanges[groupIds[i]] = {min: 0, max: 0, yAxisOrientation: group.options.yAxisOrientation, ignore: true};
  642. // combine data
  643. for (var j = 0; j < groupData.length; j++) {
  644. barCombinedData.push({
  645. x: groupData[j].x,
  646. y: groupData[j].y,
  647. groupId: groupIds[i]
  648. });
  649. }
  650. }
  651. }
  652. if (barCombinedDataLeft.length > 0) {
  653. // sort by time and by group
  654. barCombinedDataLeft.sort(function (a, b) {
  655. if (a.x == b.x) {
  656. return a.groupId - b.groupId;
  657. } else {
  658. return a.x - b.x;
  659. }
  660. })
  661. var intersections = {};
  662. this._getDataIntersections(intersections, barCombinedDataLeft);
  663. groupRanges["__barchartLeft"] = this._getStackedBarYRange(intersections, barCombinedDataLeft);
  664. groupRanges["__barchartLeft"].yAxisOrientation = "left";
  665. groupIds.push("__barchartLeft");
  666. }
  667. if (barCombinedDataRight.length > 0) {
  668. // sort by time and by group
  669. barCombinedDataRight.sort(function (a, b) {
  670. if (a.x == b.x) {
  671. return a.groupId - b.groupId;
  672. } else {
  673. return a.x - b.x;
  674. }
  675. })
  676. var intersections = {};
  677. this._getDataIntersections(intersections, barCombinedDataRight);
  678. groupRanges["__barchartRight"] = this._getStackedBarYRange(intersections, barCombinedDataRight);
  679. groupRanges["__barchartRight"].yAxisOrientation = "right";
  680. groupIds.push("__barchartRight");
  681. }
  682. }
  683. };
  684. LineGraph.prototype._getStackedBarYRange = function (intersections, combinedData) {
  685. var key;
  686. var yMin = combinedData[0].y;
  687. var yMax = combinedData[0].y;
  688. for (var i = 0; i < combinedData.length; i++) {
  689. key = combinedData[i].x;
  690. if (intersections[key] === undefined) {
  691. yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin;
  692. yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax;
  693. }
  694. else {
  695. intersections[key].accumulated += combinedData[i].y;
  696. }
  697. }
  698. for (var xpos in intersections) {
  699. if (intersections.hasOwnProperty(xpos)) {
  700. yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin;
  701. yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax;
  702. }
  703. }
  704. return {min: yMin, max: yMax};
  705. };
  706. /**
  707. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  708. * @param {array} groupIds
  709. * @private
  710. */
  711. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  712. var changeCalled = false;
  713. var yAxisLeftUsed = false;
  714. var yAxisRightUsed = false;
  715. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  716. // if groups are present
  717. if (groupIds.length > 0) {
  718. for (var i = 0; i < groupIds.length; 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. if (yAxisLeftUsed == true) {
  735. this.yAxisLeft.setRange(minLeft, maxLeft);
  736. }
  737. if (yAxisRightUsed == true) {
  738. this.yAxisRight.setRange(minRight, maxRight);
  739. }
  740. }
  741. changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled;
  742. changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled;
  743. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  744. this.yAxisLeft.drawIcons = true;
  745. this.yAxisRight.drawIcons = true;
  746. }
  747. else {
  748. this.yAxisLeft.drawIcons = false;
  749. this.yAxisRight.drawIcons = false;
  750. }
  751. this.yAxisRight.master = !yAxisLeftUsed;
  752. if (this.yAxisRight.master == false) {
  753. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  754. else {this.yAxisLeft.lineOffset = 0;}
  755. changeCalled = this.yAxisLeft.redraw() || changeCalled;
  756. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  757. changeCalled = this.yAxisRight.redraw() || changeCalled;
  758. }
  759. else {
  760. changeCalled = this.yAxisRight.redraw() || changeCalled;
  761. }
  762. // clean the accumulated lists
  763. if (groupIds.indexOf("__barchartLeft") != -1) {
  764. groupIds.splice(groupIds.indexOf("__barchartLeft"),1);
  765. }
  766. if (groupIds.indexOf("__barchartRight") != -1) {
  767. groupIds.splice(groupIds.indexOf("__barchartRight"),1);
  768. }
  769. return changeCalled;
  770. };
  771. /**
  772. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  773. *
  774. * @param {boolean} axisUsed
  775. * @returns {boolean}
  776. * @private
  777. * @param axis
  778. */
  779. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  780. var changed = false;
  781. if (axisUsed == false) {
  782. if (axis.dom.frame.parentNode) {
  783. axis.hide();
  784. changed = true;
  785. }
  786. }
  787. else {
  788. if (!axis.dom.frame.parentNode) {
  789. axis.show();
  790. changed = true;
  791. }
  792. }
  793. return changed;
  794. };
  795. /**
  796. * draw a bar graph
  797. * @param datapoints
  798. * @param group
  799. */
  800. LineGraph.prototype._drawBarGraphs = function (groupIds, processedGroupData) {
  801. var combinedData = [];
  802. var intersections = {};
  803. var coreDistance;
  804. var key;
  805. var group;
  806. var i,j;
  807. var barPoints = 0;
  808. // combine all barchart data
  809. for (i = 0; i < groupIds.length; i++) {
  810. group = this.groups[groupIds[i]];
  811. if (group.options.style == 'bar') {
  812. if (group.visible == true) {
  813. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  814. combinedData.push({
  815. x: processedGroupData[groupIds[i]][j].x,
  816. y: processedGroupData[groupIds[i]][j].y,
  817. groupId: groupIds[i]
  818. });
  819. barPoints += 1;
  820. }
  821. }
  822. }
  823. }
  824. if (barPoints == 0) {return;}
  825. // sort by time and by group
  826. combinedData.sort(function (a, b) {
  827. if (a.x == b.x) {
  828. return a.groupId - b.groupId;
  829. } else {
  830. return a.x - b.x;
  831. }
  832. });
  833. // get intersections
  834. this._getDataIntersections(intersections, combinedData);
  835. // plot barchart
  836. for (i = 0; i < combinedData.length; i++) {
  837. group = this.groups[combinedData[i].groupId];
  838. var minWidth = 0.1 * group.options.barChart.width;
  839. key = combinedData[i].x;
  840. var heightOffset = 0;
  841. if (intersections[key] === undefined) {
  842. if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);}
  843. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));}
  844. var drawData = this._getSafeDrawData(coreDistance, group, minWidth);
  845. }
  846. else {
  847. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  848. var prevKey = i - (intersections[key].resolved + 1);
  849. if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);}
  850. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));}
  851. var drawData = this._getSafeDrawData(coreDistance, group, minWidth);
  852. intersections[key].resolved += 1;
  853. if (group.options.barChart.handleOverlap == 'stack') {
  854. heightOffset = intersections[key].accumulated;
  855. intersections[key].accumulated += group.zeroPosition - combinedData[i].y;
  856. }
  857. else if (group.options.barChart.handleOverlap == 'sideBySide') {
  858. drawData.width = drawData.width / intersections[key].amount;
  859. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  860. if (group.options.barChart.align == 'left') {offset -= 0.5*drawData.width;}
  861. else if (group.options.barChart.align == 'right') {offset += 0.5*drawData.width;}
  862. }
  863. }
  864. 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);
  865. // draw points
  866. if (group.options.drawPoints.enabled == true) {
  867. DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, group, this.svgElements, this.svg);
  868. }
  869. }
  870. };
  871. LineGraph.prototype._getDataIntersections = function (intersections, combinedData) {
  872. // get intersections
  873. var coreDistance;
  874. for (var i = 0; i < combinedData.length; i++) {
  875. if (i + 1 < combinedData.length) {
  876. coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x);
  877. }
  878. if (i > 0) {
  879. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x));
  880. }
  881. if (coreDistance == 0) {
  882. if (intersections[combinedData[i].x] === undefined) {
  883. intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0};
  884. }
  885. intersections[combinedData[i].x].amount += 1;
  886. }
  887. }
  888. };
  889. //LineGraph.prototype._accumulate = function (intersections, combinedData) {
  890. LineGraph.prototype._getSafeDrawData = function (coreDistance, group, minWidth) {
  891. var width, offset;
  892. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  893. width = coreDistance < minWidth ? minWidth : coreDistance;
  894. offset = 0; // recalculate offset with the new width;
  895. if (group.options.barChart.align == 'left') {
  896. offset -= 0.5 * coreDistance;
  897. }
  898. else if (group.options.barChart.align == 'right') {
  899. offset += 0.5 * coreDistance;
  900. }
  901. }
  902. else {
  903. // no collisions, plot with default settings
  904. width = group.options.barChart.width;
  905. offset = 0;
  906. if (group.options.barChart.align == 'left') {
  907. offset -= 0.5 * group.options.barChart.width;
  908. }
  909. else if (group.options.barChart.align == 'right') {
  910. offset += 0.5 * group.options.barChart.width;
  911. }
  912. }
  913. return {width: width, offset: offset};
  914. };
  915. /**
  916. * draw a line graph
  917. *
  918. * @param datapoints
  919. * @param group
  920. */
  921. LineGraph.prototype._drawLineGraph = function (dataset, group) {
  922. if (dataset != null) {
  923. if (dataset.length > 0) {
  924. var path, d;
  925. var svgHeight = Number(this.svg.style.height.replace("px",""));
  926. path = DOMutil.getSVGElement('path', this.svgElements, this.svg);
  927. path.setAttributeNS(null, "class", group.className);
  928. // construct path from dataset
  929. if (group.options.catmullRom.enabled == true) {
  930. d = this._catmullRom(dataset, group);
  931. }
  932. else {
  933. d = this._linear(dataset);
  934. }
  935. // append with points for fill and finalize the path
  936. if (group.options.shaded.enabled == true) {
  937. var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg);
  938. var dFill;
  939. if (group.options.shaded.orientation == 'top') {
  940. dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0;
  941. }
  942. else {
  943. dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight;
  944. }
  945. fillPath.setAttributeNS(null, "class", group.className + " fill");
  946. fillPath.setAttributeNS(null, "d", dFill);
  947. }
  948. // copy properties to path for drawing.
  949. path.setAttributeNS(null, "d", "M" + d);
  950. // draw points
  951. if (group.options.drawPoints.enabled == true) {
  952. this._drawPoints(dataset, group, this.svgElements, this.svg);
  953. }
  954. }
  955. }
  956. };
  957. /**
  958. * draw the data points
  959. *
  960. * @param dataset
  961. * @param JSONcontainer
  962. * @param svg
  963. * @param group
  964. */
  965. LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) {
  966. if (offset === undefined) {offset = 0;}
  967. for (var i = 0; i < dataset.length; i++) {
  968. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg);
  969. }
  970. };
  971. /**
  972. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  973. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  974. * the yAxis.
  975. *
  976. * @param datapoints
  977. * @returns {Array}
  978. * @private
  979. */
  980. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  981. var extractedData = [];
  982. var xValue, yValue;
  983. var toScreen = this.body.util.toScreen;
  984. for (var i = 0; i < datapoints.length; i++) {
  985. xValue = toScreen(datapoints[i].x) + this.width - 1;
  986. yValue = datapoints[i].y;
  987. extractedData.push({x: xValue, y: yValue});
  988. }
  989. return extractedData;
  990. };
  991. /**
  992. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  993. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  994. * the yAxis.
  995. *
  996. * @param datapoints
  997. * @returns {Array}
  998. * @private
  999. */
  1000. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  1001. var extractedData = [];
  1002. var xValue, yValue;
  1003. var toScreen = this.body.util.toScreen;
  1004. var axis = this.yAxisLeft;
  1005. var svgHeight = Number(this.svg.style.height.replace("px",""));
  1006. if (group.options.yAxisOrientation == 'right') {
  1007. axis = this.yAxisRight;
  1008. }
  1009. for (var i = 0; i < datapoints.length; i++) {
  1010. xValue = toScreen(datapoints[i].x) + this.width - 1;
  1011. yValue = Math.round(axis.convertValue(datapoints[i].y));
  1012. extractedData.push({x: xValue, y: yValue});
  1013. }
  1014. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  1015. return extractedData;
  1016. };
  1017. /**
  1018. * This uses an uniform parametrization of the CatmullRom algorithm:
  1019. * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al.
  1020. * @param data
  1021. * @returns {string}
  1022. * @private
  1023. */
  1024. LineGraph.prototype._catmullRomUniform = function(data) {
  1025. // catmull rom
  1026. var p0, p1, p2, p3, bp1, bp2;
  1027. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  1028. var normalization = 1/6;
  1029. var length = data.length;
  1030. for (var i = 0; i < length - 1; i++) {
  1031. p0 = (i == 0) ? data[0] : data[i-1];
  1032. p1 = data[i];
  1033. p2 = data[i+1];
  1034. p3 = (i + 2 < length) ? data[i+2] : p2;
  1035. // Catmull-Rom to Cubic Bezier conversion matrix
  1036. // 0 1 0 0
  1037. // -1/6 1 1/6 0
  1038. // 0 1/6 1 -1/6
  1039. // 0 0 1 0
  1040. // bp0 = { x: p1.x, y: p1.y };
  1041. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  1042. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  1043. // bp0 = { x: p2.x, y: p2.y };
  1044. d += "C" +
  1045. bp1.x + "," +
  1046. bp1.y + " " +
  1047. bp2.x + "," +
  1048. bp2.y + " " +
  1049. p2.x + "," +
  1050. p2.y + " ";
  1051. }
  1052. return d;
  1053. };
  1054. /**
  1055. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  1056. * By default, the centripetal parameterization is used because this gives the nicest results.
  1057. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  1058. *
  1059. * One optimization can be used to reuse distances since this is a sliding window approach.
  1060. * @param data
  1061. * @returns {string}
  1062. * @private
  1063. */
  1064. LineGraph.prototype._catmullRom = function(data, group) {
  1065. var alpha = group.options.catmullRom.alpha;
  1066. if (alpha == 0 || alpha === undefined) {
  1067. return this._catmullRomUniform(data);
  1068. }
  1069. else {
  1070. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  1071. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  1072. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  1073. var length = data.length;
  1074. for (var i = 0; i < length - 1; i++) {
  1075. p0 = (i == 0) ? data[0] : data[i-1];
  1076. p1 = data[i];
  1077. p2 = data[i+1];
  1078. p3 = (i + 2 < length) ? data[i+2] : p2;
  1079. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  1080. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  1081. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  1082. // Catmull-Rom to Cubic Bezier conversion matrix
  1083. //
  1084. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  1085. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  1086. //
  1087. // [ 0 1 0 0 ]
  1088. // [ -d2^2a/N A/N d1^2a/N 0 ]
  1089. // [ 0 d3^2a/M B/M -d2^2a/M ]
  1090. // [ 0 0 1 0 ]
  1091. // [ 0 1 0 0 ]
  1092. // [ -d2pow2a/N A/N d1pow2a/N 0 ]
  1093. // [ 0 d3pow2a/M B/M -d2pow2a/M ]
  1094. // [ 0 0 1 0 ]
  1095. d3powA = Math.pow(d3, alpha);
  1096. d3pow2A = Math.pow(d3,2*alpha);
  1097. d2powA = Math.pow(d2, alpha);
  1098. d2pow2A = Math.pow(d2,2*alpha);
  1099. d1powA = Math.pow(d1, alpha);
  1100. d1pow2A = Math.pow(d1,2*alpha);
  1101. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  1102. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  1103. N = 3*d1powA * (d1powA + d2powA);
  1104. if (N > 0) {N = 1 / N;}
  1105. M = 3*d3powA * (d3powA + d2powA);
  1106. if (M > 0) {M = 1 / M;}
  1107. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  1108. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  1109. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  1110. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  1111. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  1112. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  1113. d += "C" +
  1114. bp1.x + "," +
  1115. bp1.y + " " +
  1116. bp2.x + "," +
  1117. bp2.y + " " +
  1118. p2.x + "," +
  1119. p2.y + " ";
  1120. }
  1121. return d;
  1122. }
  1123. };
  1124. /**
  1125. * this generates the SVG path for a linear drawing between datapoints.
  1126. * @param data
  1127. * @returns {string}
  1128. * @private
  1129. */
  1130. LineGraph.prototype._linear = function(data) {
  1131. // linear
  1132. var d = "";
  1133. for (var i = 0; i < data.length; i++) {
  1134. if (i == 0) {
  1135. d += data[i].x + "," + data[i].y;
  1136. }
  1137. else {
  1138. d += " " + data[i].x + "," + data[i].y;
  1139. }
  1140. }
  1141. return d;
  1142. };
  1143. module.exports = LineGraph;