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.

1063 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. preprocessedGroup = this._preprocessData(groupData, group);
  545. groupRanges.push({min: preprocessedGroup.min, max: preprocessedGroup.max});
  546. preprocessedGroupData.push(preprocessedGroup.data);
  547. }
  548. else {
  549. groupRanges.push({});
  550. preprocessedGroupData.push([]);
  551. }
  552. }
  553. // update the Y axis first, we use this data to draw at the correct Y points
  554. // changeCalled is required to clean the SVG on a change emit.
  555. changeCalled = this._updateYAxis(groupIds, groupRanges);
  556. if (changeCalled == true) {
  557. DOMutil.cleanupElements(this.svgElements);
  558. this.body.emitter.emit("change");
  559. return;
  560. }
  561. // with the yAxis scaled correctly, use this to get the Y values of the points.
  562. for (i = 0; i < groupIds.length; i++) {
  563. group = this.groups[groupIds[i]];
  564. processedGroupData.push(this._convertYvalues(preprocessedGroupData[i],group))
  565. }
  566. // draw the groups
  567. for (i = 0; i < groupIds.length; i++) {
  568. group = this.groups[groupIds[i]];
  569. if (group.visible == true) {
  570. if (group.options.style == 'line') {
  571. this._drawLineGraph(processedGroupData[i], group);
  572. }
  573. else {
  574. this._drawBarGraph (processedGroupData[i], group);
  575. }
  576. }
  577. }
  578. }
  579. }
  580. // cleanup unused svg elements
  581. DOMutil.cleanupElements(this.svgElements);
  582. };
  583. /**
  584. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  585. * @param {array} groupIds
  586. * @private
  587. */
  588. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  589. var changeCalled = false;
  590. var yAxisLeftUsed = false;
  591. var yAxisRightUsed = false;
  592. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  593. var orientation = 'left';
  594. // if groups are present
  595. if (groupIds.length > 0) {
  596. for (var i = 0; i < groupIds.length; i++) {
  597. orientation = 'left';
  598. var group = this.groups[groupIds[i]];
  599. if (group.visible == true) {
  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. }
  617. console.log(yAxisRightUsed)
  618. if (yAxisLeftUsed == true) {
  619. this.yAxisLeft.setRange(minLeft, maxLeft);
  620. }
  621. if (yAxisRightUsed == true) {
  622. this.yAxisRight.setRange(minRight, maxRight);
  623. }
  624. }
  625. changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled;
  626. changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled;
  627. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  628. this.yAxisLeft.drawIcons = true;
  629. this.yAxisRight.drawIcons = true;
  630. }
  631. else {
  632. this.yAxisLeft.drawIcons = false;
  633. this.yAxisRight.drawIcons = false;
  634. }
  635. this.yAxisRight.master = !yAxisLeftUsed;
  636. if (this.yAxisRight.master == false) {
  637. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  638. else {this.yAxisLeft.lineOffset = 0;}
  639. changeCalled = this.yAxisLeft.redraw() || changeCalled;
  640. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  641. changeCalled = this.yAxisRight.redraw() || changeCalled;
  642. }
  643. else {
  644. changeCalled = this.yAxisRight.redraw() || changeCalled;
  645. }
  646. return changeCalled;
  647. };
  648. /**
  649. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  650. *
  651. * @param {boolean} axisUsed
  652. * @returns {boolean}
  653. * @private
  654. * @param axis
  655. */
  656. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  657. var changed = false;
  658. if (axisUsed == false) {
  659. if (axis.dom.frame.parentNode) {
  660. axis.hide();
  661. changed = true;
  662. }
  663. }
  664. else {
  665. if (!axis.dom.frame.parentNode) {
  666. axis.show();
  667. changed = true;
  668. }
  669. }
  670. return changed;
  671. };
  672. /**
  673. * draw a bar graph
  674. * @param datapoints
  675. * @param group
  676. */
  677. LineGraph.prototype._drawBarGraph = function (dataset, group) {
  678. if (dataset != null) {
  679. if (dataset.length > 0) {
  680. var coreDistance;
  681. var minWidth = 0.1 * group.options.barChart.width;
  682. var offset = 0;
  683. var width = group.options.barChart.width;
  684. if (group.options.barChart.align == 'left') {offset -= 0.5*width;}
  685. else if (group.options.barChart.align == 'right') {offset += 0.5*width;}
  686. for (var i = 0; i < dataset.length; i++) {
  687. // dynammically downscale the width so there is no overlap up to 1/10th the original width
  688. if (i+1 < dataset.length) {coreDistance = Math.abs(dataset[i+1].x - dataset[i].x);}
  689. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[i-1].x - dataset[i].x));}
  690. if (coreDistance < width) {width = coreDistance < minWidth ? minWidth : coreDistance;}
  691. DOMutil.drawBar(dataset[i].x + offset, dataset[i].y, width, group.zeroPosition - dataset[i].y, group.className + ' bar', this.svgElements, this.svg);
  692. }
  693. // draw points
  694. if (group.options.drawPoints.enabled == true) {
  695. this._drawPoints(dataset, group, this.svgElements, this.svg, offset);
  696. }
  697. }
  698. }
  699. };
  700. /**
  701. * draw a line graph
  702. *
  703. * @param datapoints
  704. * @param group
  705. */
  706. LineGraph.prototype._drawLineGraph = function (dataset, group) {
  707. if (dataset != null) {
  708. if (dataset.length > 0) {
  709. var path, d;
  710. var svgHeight = Number(this.svg.style.height.replace("px",""));
  711. path = DOMutil.getSVGElement('path', this.svgElements, this.svg);
  712. path.setAttributeNS(null, "class", group.className);
  713. // construct path from dataset
  714. if (group.options.catmullRom.enabled == true) {
  715. d = this._catmullRom(dataset, group);
  716. }
  717. else {
  718. d = this._linear(dataset);
  719. }
  720. // append with points for fill and finalize the path
  721. if (group.options.shaded.enabled == true) {
  722. var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg);
  723. var dFill;
  724. if (group.options.shaded.orientation == 'top') {
  725. dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0;
  726. }
  727. else {
  728. dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight;
  729. }
  730. fillPath.setAttributeNS(null, "class", group.className + " fill");
  731. fillPath.setAttributeNS(null, "d", dFill);
  732. }
  733. // copy properties to path for drawing.
  734. path.setAttributeNS(null, "d", "M" + d);
  735. // draw points
  736. if (group.options.drawPoints.enabled == true) {
  737. this._drawPoints(dataset, group, this.svgElements, this.svg);
  738. }
  739. }
  740. }
  741. };
  742. /**
  743. * draw the data points
  744. *
  745. * @param dataset
  746. * @param JSONcontainer
  747. * @param svg
  748. * @param group
  749. */
  750. LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) {
  751. if (offset === undefined) {offset = 0;}
  752. for (var i = 0; i < dataset.length; i++) {
  753. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg);
  754. }
  755. };
  756. /**
  757. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  758. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  759. * the yAxis.
  760. *
  761. * @param datapoints
  762. * @returns {Array}
  763. * @private
  764. */
  765. LineGraph.prototype._preprocessData = function (datapoints, group) {
  766. var extractedData = [];
  767. var xValue, yValue;
  768. var toScreen = this.body.util.toScreen;
  769. var increment = 1;
  770. var amountOfPoints = datapoints.length;
  771. var yMin = datapoints[0].y;
  772. var yMax = datapoints[0].y;
  773. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  774. // of width changing of the yAxis.
  775. if (group.options.sampling == true) {
  776. var xDistance = this.body.util.toGlobalScreen(datapoints[datapoints.length-1].x) - this.body.util.toGlobalScreen(datapoints[0].x);
  777. var pointsPerPixel = amountOfPoints/xDistance;
  778. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1,Math.round(pointsPerPixel)));
  779. }
  780. for (var i = 0; i < amountOfPoints; i += increment) {
  781. xValue = toScreen(datapoints[i].x) + this.width - 1;
  782. yValue = datapoints[i].y;
  783. extractedData.push({x: xValue, y: yValue});
  784. yMin = yMin > yValue ? yValue : yMin;
  785. yMax = yMax < yValue ? yValue : yMax;
  786. }
  787. // extractedData.sort(function (a,b) {return a.x - b.x;});
  788. return {min: yMin, max: yMax, data: extractedData};
  789. };
  790. /**
  791. * This uses the DataAxis object to generate the correct Y coordinate on the SVG window. It uses the
  792. * util function toScreen to get the x coordinate from the timestamp.
  793. *
  794. * @param datapoints
  795. * @param options
  796. * @returns {Array}
  797. * @private
  798. */
  799. LineGraph.prototype._convertYvalues = function (datapoints, group) {
  800. var extractedData = [];
  801. var xValue, yValue;
  802. var axis = this.yAxisLeft;
  803. var svgHeight = Number(this.svg.style.height.replace("px",""));
  804. if (group.options.yAxisOrientation == 'right') {
  805. axis = this.yAxisRight;
  806. }
  807. for (var i = 0; i < datapoints.length; i++) {
  808. xValue = datapoints[i].x;
  809. yValue = Math.round(axis.convertValue(datapoints[i].y));
  810. extractedData.push({x: xValue, y: yValue});
  811. }
  812. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  813. // extractedData.sort(function (a,b) {return a.x - b.x;});
  814. return extractedData;
  815. };
  816. /**
  817. * This uses an uniform parametrization of the CatmullRom algorithm:
  818. * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al.
  819. * @param data
  820. * @returns {string}
  821. * @private
  822. */
  823. LineGraph.prototype._catmullRomUniform = function(data) {
  824. // catmull rom
  825. var p0, p1, p2, p3, bp1, bp2;
  826. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  827. var normalization = 1/6;
  828. var length = data.length;
  829. for (var i = 0; i < length - 1; i++) {
  830. p0 = (i == 0) ? data[0] : data[i-1];
  831. p1 = data[i];
  832. p2 = data[i+1];
  833. p3 = (i + 2 < length) ? data[i+2] : p2;
  834. // Catmull-Rom to Cubic Bezier conversion matrix
  835. // 0 1 0 0
  836. // -1/6 1 1/6 0
  837. // 0 1/6 1 -1/6
  838. // 0 0 1 0
  839. // bp0 = { x: p1.x, y: p1.y };
  840. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  841. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  842. // bp0 = { x: p2.x, y: p2.y };
  843. d += "C" +
  844. bp1.x + "," +
  845. bp1.y + " " +
  846. bp2.x + "," +
  847. bp2.y + " " +
  848. p2.x + "," +
  849. p2.y + " ";
  850. }
  851. return d;
  852. };
  853. /**
  854. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  855. * By default, the centripetal parameterization is used because this gives the nicest results.
  856. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  857. *
  858. * One optimization can be used to reuse distances since this is a sliding window approach.
  859. * @param data
  860. * @returns {string}
  861. * @private
  862. */
  863. LineGraph.prototype._catmullRom = function(data, group) {
  864. var alpha = group.options.catmullRom.alpha;
  865. if (alpha == 0 || alpha === undefined) {
  866. return this._catmullRomUniform(data);
  867. }
  868. else {
  869. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  870. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  871. var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " ";
  872. var length = data.length;
  873. for (var i = 0; i < length - 1; i++) {
  874. p0 = (i == 0) ? data[0] : data[i-1];
  875. p1 = data[i];
  876. p2 = data[i+1];
  877. p3 = (i + 2 < length) ? data[i+2] : p2;
  878. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  879. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  880. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  881. // Catmull-Rom to Cubic Bezier conversion matrix
  882. //
  883. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  884. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  885. //
  886. // [ 0 1 0 0 ]
  887. // [ -d2^2a/N A/N d1^2a/N 0 ]
  888. // [ 0 d3^2a/M B/M -d2^2a/M ]
  889. // [ 0 0 1 0 ]
  890. // [ 0 1 0 0 ]
  891. // [ -d2pow2a/N A/N d1pow2a/N 0 ]
  892. // [ 0 d3pow2a/M B/M -d2pow2a/M ]
  893. // [ 0 0 1 0 ]
  894. d3powA = Math.pow(d3, alpha);
  895. d3pow2A = Math.pow(d3,2*alpha);
  896. d2powA = Math.pow(d2, alpha);
  897. d2pow2A = Math.pow(d2,2*alpha);
  898. d1powA = Math.pow(d1, alpha);
  899. d1pow2A = Math.pow(d1,2*alpha);
  900. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  901. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  902. N = 3*d1powA * (d1powA + d2powA);
  903. if (N > 0) {N = 1 / N;}
  904. M = 3*d3powA * (d3powA + d2powA);
  905. if (M > 0) {M = 1 / M;}
  906. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  907. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  908. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  909. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  910. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  911. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  912. d += "C" +
  913. bp1.x + "," +
  914. bp1.y + " " +
  915. bp2.x + "," +
  916. bp2.y + " " +
  917. p2.x + "," +
  918. p2.y + " ";
  919. }
  920. return d;
  921. }
  922. };
  923. /**
  924. * this generates the SVG path for a linear drawing between datapoints.
  925. * @param data
  926. * @returns {string}
  927. * @private
  928. */
  929. LineGraph.prototype._linear = function(data) {
  930. // linear
  931. var d = "";
  932. for (var i = 0; i < data.length; i++) {
  933. if (i == 0) {
  934. d += data[i].x + "," + data[i].y;
  935. }
  936. else {
  937. d += " " + data[i].x + "," + data[i].y;
  938. }
  939. }
  940. return d;
  941. };
  942. module.exports = LineGraph;