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.

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