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.

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