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.

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