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.

1130 lines
35 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
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. allowOverlap: true,
  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, groupData, preprocessedGroup, 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. groupIds.push(groupId);
  507. }
  508. }
  509. // this is the range of the SVG canvas
  510. var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width);
  511. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  512. // first select and preprocess the data from the datasets.
  513. // the groups have their preselection of data, we now loop over this data to see
  514. // what data we need to draw. Sorted data is much faster.
  515. // more optimization is possible by doing the sampling before and using the binary search
  516. // to find the end date to determine the increment.
  517. if (groupIds.length > 0) {
  518. for (i = 0; i < groupIds.length; i++) {
  519. group = this.groups[groupIds[i]];
  520. if (group.visible == true) {
  521. groupData = [];
  522. // optimization for sorted data
  523. if (group.options.sort == true) {
  524. var guess = Math.max(0,util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before'));
  525. for (var j = guess; j < group.itemsData.length; j++) {
  526. var item = group.itemsData[j];
  527. if (item !== undefined) {
  528. if (item.x > maxDate) {
  529. groupData.push(item);
  530. break;
  531. }
  532. else {
  533. groupData.push(item);
  534. }
  535. }
  536. }
  537. }
  538. else {
  539. for (var j = 0; j < group.itemsData.length; j++) {
  540. var item = group.itemsData[j];
  541. if (item !== undefined) {
  542. if (item.x > minDate && item.x < maxDate) {
  543. groupData.push(item);
  544. }
  545. }
  546. }
  547. }
  548. // preprocess, split into ranges and data
  549. if (groupData.length > 0) {
  550. preprocessedGroup = this._preprocessData(groupData, group);
  551. groupRanges.push({min: preprocessedGroup.min, max: preprocessedGroup.max});
  552. preprocessedGroupData.push(preprocessedGroup.data);
  553. }
  554. else {
  555. groupRanges.push({});
  556. preprocessedGroupData.push([]);
  557. }
  558. }
  559. else {
  560. groupRanges.push({});
  561. preprocessedGroupData.push([]);
  562. }
  563. }
  564. // update the Y axis first, we use this data to draw at the correct Y points
  565. // changeCalled is required to clean the SVG on a change emit.
  566. changeCalled = this._updateYAxis(groupIds, groupRanges);
  567. if (changeCalled == true) {
  568. DOMutil.cleanupElements(this.svgElements);
  569. this.body.emitter.emit("change");
  570. return;
  571. }
  572. // with the yAxis scaled correctly, use this to get the Y values of the points.
  573. for (i = 0; i < groupIds.length; i++) {
  574. group = this.groups[groupIds[i]];
  575. processedGroupData.push(this._convertYvalues(preprocessedGroupData[i],group))
  576. }
  577. // draw the groups
  578. for (i = 0; i < groupIds.length; i++) {
  579. group = this.groups[groupIds[i]];
  580. if (group.visible == true) {
  581. if (group.options.style == 'line') {
  582. this._drawLineGraph(processedGroupData[i], group);
  583. }
  584. else {
  585. this._drawBarGraph (processedGroupData[i], group);
  586. }
  587. }
  588. }
  589. }
  590. }
  591. // cleanup unused svg elements
  592. DOMutil.cleanupElements(this.svgElements);
  593. };
  594. /**
  595. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  596. * @param {array} groupIds
  597. * @private
  598. */
  599. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  600. var changeCalled = false;
  601. var yAxisLeftUsed = false;
  602. var yAxisRightUsed = false;
  603. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  604. var orientation = 'left';
  605. // if groups are present
  606. if (groupIds.length > 0) {
  607. for (var i = 0; i < groupIds.length; i++) {
  608. orientation = 'left';
  609. var group = this.groups[groupIds[i]];
  610. if (group.visible == true) {
  611. if (group.options.yAxisOrientation == 'right') {
  612. orientation = 'right';
  613. }
  614. minVal = groupRanges[i].min;
  615. maxVal = groupRanges[i].max;
  616. if (orientation == 'left') {
  617. yAxisLeftUsed = true;
  618. minLeft = minLeft > minVal ? minVal : minLeft;
  619. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  620. }
  621. else {
  622. yAxisRightUsed = true;
  623. minRight = minRight > minVal ? minVal : minRight;
  624. maxRight = maxRight < maxVal ? maxVal : maxRight;
  625. }
  626. }
  627. }
  628. if (yAxisLeftUsed == true) {
  629. this.yAxisLeft.setRange(minLeft, maxLeft);
  630. }
  631. if (yAxisRightUsed == true) {
  632. this.yAxisRight.setRange(minRight, maxRight);
  633. }
  634. }
  635. changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled;
  636. changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled;
  637. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  638. this.yAxisLeft.drawIcons = true;
  639. this.yAxisRight.drawIcons = true;
  640. }
  641. else {
  642. this.yAxisLeft.drawIcons = false;
  643. this.yAxisRight.drawIcons = false;
  644. }
  645. this.yAxisRight.master = !yAxisLeftUsed;
  646. if (this.yAxisRight.master == false) {
  647. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  648. else {this.yAxisLeft.lineOffset = 0;}
  649. changeCalled = this.yAxisLeft.redraw() || changeCalled;
  650. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  651. changeCalled = this.yAxisRight.redraw() || changeCalled;
  652. }
  653. else {
  654. changeCalled = this.yAxisRight.redraw() || changeCalled;
  655. }
  656. return changeCalled;
  657. };
  658. /**
  659. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  660. *
  661. * @param {boolean} axisUsed
  662. * @returns {boolean}
  663. * @private
  664. * @param axis
  665. */
  666. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  667. var changed = false;
  668. if (axisUsed == false) {
  669. if (axis.dom.frame.parentNode) {
  670. axis.hide();
  671. changed = true;
  672. }
  673. }
  674. else {
  675. if (!axis.dom.frame.parentNode) {
  676. axis.show();
  677. changed = true;
  678. }
  679. }
  680. return changed;
  681. };
  682. /**
  683. * draw a bar graph
  684. * @param datapoints
  685. * @param group
  686. */
  687. LineGraph.prototype._drawBarGraph = function (dataset, group) {
  688. if (dataset != null) {
  689. if (dataset.length > 0) {
  690. var coreDistance;
  691. var minWidth = 0.1 * group.options.barChart.width;
  692. var offset = 0;
  693. // check for intersections
  694. var intersections = {};
  695. for (var i = 0; i < dataset.length; i++) {
  696. if (i+1 < dataset.length) {coreDistance = Math.abs(dataset[i+1].x - dataset[i].x);}
  697. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[i-1].x - dataset[i].x));}
  698. if (coreDistance == 0) {
  699. if (intersections[dataset[i].x] === undefined) {
  700. intersections[dataset[i].x] = {amount:0, resolved:0};
  701. }
  702. intersections[dataset[i].x].amount += 1;
  703. }
  704. }
  705. // plot the bargraph
  706. var key;
  707. for (var i = 0; i < dataset.length; i++) {
  708. key = dataset[i].x;
  709. if (intersections[key] === undefined) {
  710. if (i+1 < dataset.length) {coreDistance = Math.abs(dataset[i+1].x - key);}
  711. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[i-1].x - key));}
  712. var drawData = this._getSafeDrawData(coreDistance, group, minWidth);
  713. }
  714. else {
  715. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  716. var prevKey = i - (intersections[key].resolved + 1);
  717. if (nextKey < dataset.length) {coreDistance = Math.abs(dataset[nextKey].x - key);}
  718. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[prevKey].x - key));}
  719. var drawData = this._getSafeDrawData(coreDistance, group, minWidth);
  720. intersections[key].resolved += 1;
  721. if (group.options.barChart.allowOverlap == false) {
  722. drawData.width = drawData.width / intersections[key].amount;
  723. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  724. if (group.options.barChart.align == 'left') {offset -= 0.5*drawData.width;}
  725. else if (group.options.barChart.align == 'right') {offset += 0.5*drawData.width;}
  726. }
  727. }
  728. DOMutil.drawBar(dataset[i].x + drawData.offset, dataset[i].y, drawData.width, group.zeroPosition - dataset[i].y, group.className + ' bar', this.svgElements, this.svg);
  729. // draw points
  730. if (group.options.drawPoints.enabled == true) {
  731. DOMutil.drawPoint(dataset[i].x + drawData.offset, dataset[i].y, group, this.svgElements, this.svg);
  732. }
  733. }
  734. }
  735. }
  736. };
  737. LineGraph.prototype._getSafeDrawData = function (coreDistance, group, minWidth) {
  738. var width, offset;
  739. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  740. width = coreDistance < minWidth ? minWidth : coreDistance;
  741. offset = 0; // recalculate offset with the new width;
  742. if (group.options.slots) { // recalculate the shared width and offset if these options are set.
  743. width = (width / group.options.slots.total);
  744. offset = group.options.slots.slot * width - (0.5*width * (group.options.slots.total+1));
  745. }
  746. if (group.options.barChart.align == 'left') {offset -= 0.5*coreDistance;}
  747. else if (group.options.barChart.align == 'right') {offset += 0.5*coreDistance;}
  748. }
  749. else {
  750. // no collisions, plot with default settings
  751. width = group.options.barChart.width;
  752. offset = 0;
  753. if (group.options.slots) {
  754. // if the groups are sharing the same points, this allows them to be plotted side by side
  755. width = width / group.options.slots.total;
  756. offset = group.options.slots.slot * width - (0.5*width * (group.options.slots.total+1));
  757. }
  758. if (group.options.barChart.align == 'left') {offset -= 0.5*group.options.barChart.width;}
  759. else if (group.options.barChart.align == 'right') {offset += 0.5*group.options.barChart.width;}
  760. }
  761. return {width: width, offset: offset};
  762. }
  763. /**
  764. * draw a line graph
  765. *
  766. * @param datapoints
  767. * @param group
  768. */
  769. LineGraph.prototype._drawLineGraph = function (dataset, group) {
  770. if (dataset != null) {
  771. if (dataset.length > 0) {
  772. var path, d;
  773. var svgHeight = Number(this.svg.style.height.replace("px",""));
  774. path = DOMutil.getSVGElement('path', this.svgElements, this.svg);
  775. path.setAttributeNS(null, "class", group.className);
  776. // construct path from dataset
  777. if (group.options.catmullRom.enabled == true) {
  778. d = this._catmullRom(dataset, group);
  779. }
  780. else {
  781. d = this._linear(dataset);
  782. }
  783. // append with points for fill and finalize the path
  784. if (group.options.shaded.enabled == true) {
  785. var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg);
  786. var dFill;
  787. if (group.options.shaded.orientation == 'top') {
  788. dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0;
  789. }
  790. else {
  791. dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight;
  792. }
  793. fillPath.setAttributeNS(null, "class", group.className + " fill");
  794. fillPath.setAttributeNS(null, "d", dFill);
  795. }
  796. // copy properties to path for drawing.
  797. path.setAttributeNS(null, "d", "M" + d);
  798. // draw points
  799. if (group.options.drawPoints.enabled == true) {
  800. this._drawPoints(dataset, group, this.svgElements, this.svg);
  801. }
  802. }
  803. }
  804. };
  805. /**
  806. * draw the data points
  807. *
  808. * @param dataset
  809. * @param JSONcontainer
  810. * @param svg
  811. * @param group
  812. */
  813. LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) {
  814. if (offset === undefined) {offset = 0;}
  815. for (var i = 0; i < dataset.length; i++) {
  816. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg);
  817. }
  818. };
  819. /**
  820. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  821. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  822. * the yAxis.
  823. *
  824. * @param datapoints
  825. * @returns {Array}
  826. * @private
  827. */
  828. LineGraph.prototype._preprocessData = function (datapoints, group) {
  829. var extractedData = [];
  830. var xValue, yValue;
  831. var toScreen = this.body.util.toScreen;
  832. var increment = 1;
  833. var amountOfPoints = datapoints.length;
  834. var yMin = datapoints[0].y;
  835. var yMax = datapoints[0].y;
  836. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  837. // of width changing of the yAxis.
  838. if (group.options.sampling == true) {
  839. var xDistance = this.body.util.toGlobalScreen(datapoints[datapoints.length-1].x) - this.body.util.toGlobalScreen(datapoints[0].x);
  840. var pointsPerPixel = amountOfPoints/xDistance;
  841. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1,Math.round(pointsPerPixel)));
  842. }
  843. for (var i = 0; i < amountOfPoints; i += increment) {
  844. xValue = toScreen(datapoints[i].x) + this.width - 1;
  845. yValue = datapoints[i].y;
  846. extractedData.push({x: xValue, y: yValue});
  847. yMin = yMin > yValue ? yValue : yMin;
  848. yMax = yMax < yValue ? yValue : yMax;
  849. }
  850. // extractedData.sort(function (a,b) {return a.x - b.x;});
  851. return {min: yMin, max: yMax, data: extractedData};
  852. };
  853. /**
  854. * This uses the DataAxis object to generate the correct Y coordinate on the SVG window. It uses the
  855. * util function toScreen to get the x coordinate from the timestamp.
  856. *
  857. * @param datapoints
  858. * @param options
  859. * @returns {Array}
  860. * @private
  861. */
  862. LineGraph.prototype._convertYvalues = function (datapoints, group) {
  863. var extractedData = [];
  864. var xValue, yValue;
  865. var axis = this.yAxisLeft;
  866. var svgHeight = Number(this.svg.style.height.replace("px",""));
  867. if (group.options.yAxisOrientation == 'right') {
  868. axis = this.yAxisRight;
  869. }
  870. for (var i = 0; i < datapoints.length; i++) {
  871. xValue = datapoints[i].x;
  872. yValue = Math.round(axis.convertValue(datapoints[i].y));
  873. extractedData.push({x: xValue, y: yValue});
  874. }
  875. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  876. // extractedData.sort(function (a,b) {return a.x - b.x;});
  877. return extractedData;
  878. };
  879. /**
  880. * This uses an uniform parametrization of the CatmullRom algorithm:
  881. * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al.
  882. * @param data
  883. * @returns {string}
  884. * @private
  885. */
  886. LineGraph.prototype._catmullRomUniform = function(data) {
  887. // catmull rom
  888. var p0, p1, p2, p3, bp1, bp2;
  889. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  890. var normalization = 1/6;
  891. var length = data.length;
  892. for (var i = 0; i < length - 1; i++) {
  893. p0 = (i == 0) ? data[0] : data[i-1];
  894. p1 = data[i];
  895. p2 = data[i+1];
  896. p3 = (i + 2 < length) ? data[i+2] : p2;
  897. // Catmull-Rom to Cubic Bezier conversion matrix
  898. // 0 1 0 0
  899. // -1/6 1 1/6 0
  900. // 0 1/6 1 -1/6
  901. // 0 0 1 0
  902. // bp0 = { x: p1.x, y: p1.y };
  903. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  904. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  905. // bp0 = { x: p2.x, y: p2.y };
  906. d += "C" +
  907. bp1.x + "," +
  908. bp1.y + " " +
  909. bp2.x + "," +
  910. bp2.y + " " +
  911. p2.x + "," +
  912. p2.y + " ";
  913. }
  914. return d;
  915. };
  916. /**
  917. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  918. * By default, the centripetal parameterization is used because this gives the nicest results.
  919. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  920. *
  921. * One optimization can be used to reuse distances since this is a sliding window approach.
  922. * @param data
  923. * @returns {string}
  924. * @private
  925. */
  926. LineGraph.prototype._catmullRom = function(data, group) {
  927. var alpha = group.options.catmullRom.alpha;
  928. if (alpha == 0 || alpha === undefined) {
  929. return this._catmullRomUniform(data);
  930. }
  931. else {
  932. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  933. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  934. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  935. var length = data.length;
  936. for (var i = 0; i < length - 1; i++) {
  937. p0 = (i == 0) ? data[0] : data[i-1];
  938. p1 = data[i];
  939. p2 = data[i+1];
  940. p3 = (i + 2 < length) ? data[i+2] : p2;
  941. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  942. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  943. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  944. // Catmull-Rom to Cubic Bezier conversion matrix
  945. //
  946. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  947. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  948. //
  949. // [ 0 1 0 0 ]
  950. // [ -d2^2a/N A/N d1^2a/N 0 ]
  951. // [ 0 d3^2a/M B/M -d2^2a/M ]
  952. // [ 0 0 1 0 ]
  953. // [ 0 1 0 0 ]
  954. // [ -d2pow2a/N A/N d1pow2a/N 0 ]
  955. // [ 0 d3pow2a/M B/M -d2pow2a/M ]
  956. // [ 0 0 1 0 ]
  957. d3powA = Math.pow(d3, alpha);
  958. d3pow2A = Math.pow(d3,2*alpha);
  959. d2powA = Math.pow(d2, alpha);
  960. d2pow2A = Math.pow(d2,2*alpha);
  961. d1powA = Math.pow(d1, alpha);
  962. d1pow2A = Math.pow(d1,2*alpha);
  963. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  964. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  965. N = 3*d1powA * (d1powA + d2powA);
  966. if (N > 0) {N = 1 / N;}
  967. M = 3*d3powA * (d3powA + d2powA);
  968. if (M > 0) {M = 1 / M;}
  969. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  970. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  971. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  972. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  973. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  974. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  975. d += "C" +
  976. bp1.x + "," +
  977. bp1.y + " " +
  978. bp2.x + "," +
  979. bp2.y + " " +
  980. p2.x + "," +
  981. p2.y + " ";
  982. }
  983. return d;
  984. }
  985. };
  986. /**
  987. * this generates the SVG path for a linear drawing between datapoints.
  988. * @param data
  989. * @returns {string}
  990. * @private
  991. */
  992. LineGraph.prototype._linear = function(data) {
  993. // linear
  994. var d = "";
  995. for (var i = 0; i < data.length; i++) {
  996. if (i == 0) {
  997. d += data[i].x + "," + data[i].y;
  998. }
  999. else {
  1000. d += " " + data[i].x + "," + data[i].y;
  1001. }
  1002. }
  1003. return d;
  1004. };
  1005. module.exports = LineGraph;