curvedLines.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /* The MIT License
  2. Copyright (c) 2011 by Michael Zinsmaier and nergal.dev
  3. Copyright (c) 2012 by Thomas Ritou
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /*
  21. ____________________________________________________
  22. what it is:
  23. ____________________________________________________
  24. curvedLines is a plugin for flot, that tries to display lines in a smoother way.
  25. This is achieved through adding of more data points. The plugin is a data processor and can thus be used
  26. in combination with standard line / point rendering options.
  27. => 1) with large data sets you may get trouble
  28. => 2) if you want to display the points too, you have to plot them as 2nd data series over the lines
  29. => 3) consecutive x data points are not allowed to have the same value
  30. Feel free to further improve the code
  31. ____________________________________________________
  32. how to use it:
  33. ____________________________________________________
  34. var d1 = [[5,5],[7,3],[9,12]];
  35. var options = { series: { curvedLines: { active: true }}};
  36. $.plot($("#placeholder"), [{data: d1, lines: { show: true}, curvedLines: {apply: true}}], options);
  37. _____________________________________________________
  38. options:
  39. _____________________________________________________
  40. active: bool true => plugin can be used
  41. apply: bool true => series will be drawn as curved line
  42. monotonicFit: bool true => uses monotone cubic interpolation (preserve monotonicity)
  43. tension: int defines the tension parameter of the hermite spline interpolation (no effect if monotonicFit is set)
  44. nrSplinePoints: int defines the number of sample points (of the spline) in between two consecutive points
  45. deprecated options from flot prior to 1.0.0:
  46. ------------------------------------------------
  47. legacyOverride bool true => use old default
  48. OR
  49. legacyOverride optionArray
  50. {
  51. fit: bool true => forces the max,mins of the curve to be on the datapoints
  52. curvePointFactor int defines how many "virtual" points are used per "real" data point to
  53. emulate the curvedLines (points total = real points * curvePointFactor)
  54. fitPointDist: int defines the x axis distance of the additional two points that are used
  55. } to enforce the min max condition.
  56. */
  57. /*
  58. * v0.1 initial commit
  59. * v0.15 negative values should work now (outcommented a negative -> 0 hook hope it does no harm)
  60. * v0.2 added fill option (thanks to monemihir) and multi axis support (thanks to soewono effendi)
  61. * v0.3 improved saddle handling and added basic handling of Dates
  62. * v0.4 rewritten fill option (thomas ritou) mostly from original flot code (now fill between points rather than to graph bottom), corrected fill Opacity bug
  63. * v0.5 rewritten instead of implementing a own draw function CurvedLines is now based on the processDatapoints flot hook (credits go to thomas ritou).
  64. * This change breakes existing code however CurvedLines are now just many tiny straight lines to flot and therefore all flot lines options (like gradient fill,
  65. * shadow) are now supported out of the box
  66. * v0.6 flot 0.8 compatibility and some bug fixes
  67. * v0.6.x changed versioning schema
  68. *
  69. * v1.0.0 API Break marked existing implementation/options as deprecated
  70. * v1.1.0 added the new curved line calculations based on hermite splines
  71. * v1.1.1 added a rough parameter check to make sure the new options are used
  72. */
  73. (function($) {
  74. var options = {
  75. series : {
  76. curvedLines : {
  77. active : false,
  78. apply : false,
  79. monotonicFit : false,
  80. tension : 0.5,
  81. nrSplinePoints : 20,
  82. legacyOverride : undefined
  83. }
  84. }
  85. };
  86. function init(plot) {
  87. plot.hooks.processOptions.push(processOptions);
  88. //if the plugin is active register processDatapoints method
  89. function processOptions(plot, options) {
  90. if (options.series.curvedLines.active) {
  91. plot.hooks.processDatapoints.unshift(processDatapoints);
  92. }
  93. }
  94. //only if the plugin is active
  95. function processDatapoints(plot, series, datapoints) {
  96. var nrPoints = datapoints.points.length / datapoints.pointsize;
  97. var EPSILON = 0.005;
  98. //detects missplaced legacy parameters (prior v1.x.x) in the options object
  99. //this can happen if somebody upgrades to v1.x.x without adjusting the parameters or uses old examples
  100. var invalidLegacyOptions = hasInvalidParameters(series.curvedLines);
  101. if (!invalidLegacyOptions && series.curvedLines.apply == true && series.originSeries === undefined && nrPoints > (1 + EPSILON)) {
  102. if (series.lines.fill) {
  103. var pointsTop = calculateCurvePoints(datapoints, series.curvedLines, 1);
  104. var pointsBottom = calculateCurvePoints(datapoints, series.curvedLines, 2);
  105. //flot makes sure for us that we've got a second y point if fill is true !
  106. //Merge top and bottom curve
  107. datapoints.pointsize = 3;
  108. datapoints.points = [];
  109. var j = 0;
  110. var k = 0;
  111. var i = 0;
  112. var ps = 2;
  113. while (i < pointsTop.length || j < pointsBottom.length) {
  114. if (pointsTop[i] == pointsBottom[j]) {
  115. datapoints.points[k] = pointsTop[i];
  116. datapoints.points[k + 1] = pointsTop[i + 1];
  117. datapoints.points[k + 2] = pointsBottom[j + 1];
  118. j += ps;
  119. i += ps;
  120. } else if (pointsTop[i] < pointsBottom[j]) {
  121. datapoints.points[k] = pointsTop[i];
  122. datapoints.points[k + 1] = pointsTop[i + 1];
  123. datapoints.points[k + 2] = k > 0 ? datapoints.points[k - 1] : null;
  124. i += ps;
  125. } else {
  126. datapoints.points[k] = pointsBottom[j];
  127. datapoints.points[k + 1] = k > 1 ? datapoints.points[k - 2] : null;
  128. datapoints.points[k + 2] = pointsBottom[j + 1];
  129. j += ps;
  130. }
  131. k += 3;
  132. }
  133. } else if (series.lines.lineWidth > 0) {
  134. datapoints.points = calculateCurvePoints(datapoints, series.curvedLines, 1);
  135. datapoints.pointsize = 2;
  136. }
  137. }
  138. }
  139. function calculateCurvePoints(datapoints, curvedLinesOptions, yPos) {
  140. if ( typeof curvedLinesOptions.legacyOverride != 'undefined' && curvedLinesOptions.legacyOverride != false) {
  141. var defaultOptions = {
  142. fit : false,
  143. curvePointFactor : 20,
  144. fitPointDist : undefined
  145. };
  146. var legacyOptions = jQuery.extend(defaultOptions, curvedLinesOptions.legacyOverride);
  147. return calculateLegacyCurvePoints(datapoints, legacyOptions, yPos);
  148. }
  149. return calculateSplineCurvePoints(datapoints, curvedLinesOptions, yPos);
  150. }
  151. function calculateSplineCurvePoints(datapoints, curvedLinesOptions, yPos) {
  152. var points = datapoints.points;
  153. var ps = datapoints.pointsize;
  154. //create interpolant fuction
  155. var splines = createHermiteSplines(datapoints, curvedLinesOptions, yPos);
  156. var result = [];
  157. //sample the function
  158. // (the result is intependent from the input data =>
  159. // it is ok to alter the input after this method)
  160. var j = 0;
  161. for (var i = 0; i < points.length - ps; i += ps) {
  162. var curX = i;
  163. var curY = i + yPos;
  164. var xStart = points[curX];
  165. var xEnd = points[curX + ps];
  166. var xStep = (xEnd - xStart) / Number(curvedLinesOptions.nrSplinePoints);
  167. //add point
  168. result.push(points[curX]);
  169. result.push(points[curY]);
  170. //add curve point
  171. for (var x = (xStart += xStep); x < xEnd; x += xStep) {
  172. result.push(x);
  173. result.push(splines[j](x));
  174. }
  175. j++;
  176. }
  177. //add last point
  178. result.push(points[points.length - ps]);
  179. result.push(points[points.length - ps + yPos]);
  180. return result;
  181. }
  182. // Creates an array of splines, one for each segment of the original curve. Algorithm based on the wikipedia articles:
  183. //
  184. // http://de.wikipedia.org/w/index.php?title=Kubisch_Hermitescher_Spline&oldid=130168003 and
  185. // http://en.wikipedia.org/w/index.php?title=Monotone_cubic_interpolation&oldid=622341725 and the description of Fritsch-Carlson from
  186. // http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation
  187. // for a detailed description see https://github.com/MichaelZinsmaier/CurvedLines/docu
  188. function createHermiteSplines(datapoints, curvedLinesOptions, yPos) {
  189. var points = datapoints.points;
  190. var ps = datapoints.pointsize;
  191. // preparation get length (x_{k+1} - x_k) and slope s=(p_{k+1} - p_k) / (x_{k+1} - x_k) of the segments
  192. var segmentLengths = [];
  193. var segmentSlopes = [];
  194. for (var i = 0; i < points.length - ps; i += ps) {
  195. var curX = i;
  196. var curY = i + yPos;
  197. var dx = points[curX + ps] - points[curX];
  198. var dy = points[curY + ps] - points[curY];
  199. segmentLengths.push(dx);
  200. segmentSlopes.push(dy / dx);
  201. }
  202. //get the values for the desired gradients m_k for all points k
  203. //depending on the used method the formula is different
  204. var gradients = [segmentSlopes[0]];
  205. if (curvedLinesOptions.monotonicFit) {
  206. // Fritsch Carlson
  207. for (var i = 1; i < segmentLengths.length; i++) {
  208. var slope = segmentSlopes[i];
  209. var prev_slope = segmentSlopes[i - 1];
  210. if (slope * prev_slope <= 0) { // sign(prev_slope) != sign(slpe)
  211. gradients.push(0);
  212. } else {
  213. var length = segmentLengths[i];
  214. var prev_length = segmentLengths[i - 1];
  215. var common = length + prev_length;
  216. //m = 3 (prev_length + length) / ((2 length + prev_length) / prev_slope + (length + 2 prev_length) / slope)
  217. gradients.push(3 * common / ((common + length) / prev_slope + (common + prev_length) / slope));
  218. }
  219. }
  220. } else {
  221. // Cardinal spline with t € [0,1]
  222. // Catmull-Rom for t = 0
  223. for (var i = ps; i < points.length - ps; i += ps) {
  224. var curX = i;
  225. var curY = i + yPos;
  226. gradients.push(Number(curvedLinesOptions.tension) * (points[curY + ps] - points[curY - ps]) / (points[curX + ps] - points[curX - ps]));
  227. }
  228. }
  229. gradients.push(segmentSlopes[segmentSlopes.length - 1]);
  230. //get the two major coefficients (c'_{oef1} and c'_{oef2}) for each segment spline
  231. var coefs1 = [];
  232. var coefs2 = [];
  233. for (i = 0; i < segmentLengths.length; i++) {
  234. var m_k = gradients[i];
  235. var m_k_plus = gradients[i + 1];
  236. var slope = segmentSlopes[i];
  237. var invLength = 1 / segmentLengths[i];
  238. var common = m_k + m_k_plus - slope - slope;
  239. coefs1.push(common * invLength * invLength);
  240. coefs2.push((slope - common - m_k) * invLength);
  241. }
  242. //create functions with from the coefficients and capture the parameters
  243. var ret = [];
  244. for (var i = 0; i < segmentLengths.length; i ++) {
  245. var spline = function (x_k, coef1, coef2, coef3, coef4) {
  246. // spline for a segment
  247. return function (x) {
  248. var diff = x - x_k;
  249. var diffSq = diff * diff;
  250. return coef1 * diff * diffSq + coef2 * diffSq + coef3 * diff + coef4;
  251. };
  252. };
  253. ret.push(spline(points[i * ps], coefs1[i], coefs2[i], gradients[i], points[i * ps + yPos]));
  254. }
  255. return ret;
  256. };
  257. //no real idea whats going on here code mainly from https://code.google.com/p/flot/issues/detail?id=226
  258. //if fit option is selected additional datapoints get inserted before the curve calculations in nergal.dev s code.
  259. function calculateLegacyCurvePoints(datapoints, curvedLinesOptions, yPos) {
  260. var points = datapoints.points;
  261. var ps = datapoints.pointsize;
  262. var num = Number(curvedLinesOptions.curvePointFactor) * (points.length / ps);
  263. var xdata = new Array;
  264. var ydata = new Array;
  265. var curX = -1;
  266. var curY = -1;
  267. var j = 0;
  268. if (curvedLinesOptions.fit) {
  269. //insert a point before and after the "real" data point to force the line
  270. //to have a max,min at the data point.
  271. var fpDist;
  272. if ( typeof curvedLinesOptions.fitPointDist == 'undefined') {
  273. //estimate it
  274. var minX = points[0];
  275. var maxX = points[points.length - ps];
  276. fpDist = (maxX - minX) / (500 * 100);
  277. //x range / (estimated pixel length of placeholder * factor)
  278. } else {
  279. //use user defined value
  280. fpDist = Number(curvedLinesOptions.fitPointDist);
  281. }
  282. for (var i = 0; i < points.length; i += ps) {
  283. var frontX;
  284. var backX;
  285. curX = i;
  286. curY = i + yPos;
  287. //add point X s
  288. frontX = points[curX] - fpDist;
  289. backX = points[curX] + fpDist;
  290. var factor = 2;
  291. while (frontX == points[curX] || backX == points[curX]) {
  292. //inside the ulp
  293. frontX = points[curX] - (fpDist * factor);
  294. backX = points[curX] + (fpDist * factor);
  295. factor++;
  296. }
  297. //add curve points
  298. xdata[j] = frontX;
  299. ydata[j] = points[curY];
  300. j++;
  301. xdata[j] = points[curX];
  302. ydata[j] = points[curY];
  303. j++;
  304. xdata[j] = backX;
  305. ydata[j] = points[curY];
  306. j++;
  307. }
  308. } else {
  309. //just use the datapoints
  310. for (var i = 0; i < points.length; i += ps) {
  311. curX = i;
  312. curY = i + yPos;
  313. xdata[j] = points[curX];
  314. ydata[j] = points[curY];
  315. j++;
  316. }
  317. }
  318. var n = xdata.length;
  319. var y2 = new Array();
  320. var delta = new Array();
  321. y2[0] = 0;
  322. y2[n - 1] = 0;
  323. delta[0] = 0;
  324. for (var i = 1; i < n - 1; ++i) {
  325. var d = (xdata[i + 1] - xdata[i - 1]);
  326. if (d == 0) {
  327. //point before current point and after current point need some space in between
  328. return [];
  329. }
  330. var s = (xdata[i] - xdata[i - 1]) / d;
  331. var p = s * y2[i - 1] + 2;
  332. y2[i] = (s - 1) / p;
  333. delta[i] = (ydata[i + 1] - ydata[i]) / (xdata[i + 1] - xdata[i]) - (ydata[i] - ydata[i - 1]) / (xdata[i] - xdata[i - 1]);
  334. delta[i] = (6 * delta[i] / (xdata[i + 1] - xdata[i - 1]) - s * delta[i - 1]) / p;
  335. }
  336. for (var j = n - 2; j >= 0; --j) {
  337. y2[j] = y2[j] * y2[j + 1] + delta[j];
  338. }
  339. // xmax - xmin / #points
  340. var step = (xdata[n - 1] - xdata[0]) / (num - 1);
  341. var xnew = new Array;
  342. var ynew = new Array;
  343. var result = new Array;
  344. xnew[0] = xdata[0];
  345. ynew[0] = ydata[0];
  346. result.push(xnew[0]);
  347. result.push(ynew[0]);
  348. for ( j = 1; j < num; ++j) {
  349. //new x point (sampling point for the created curve)
  350. xnew[j] = xnew[0] + j * step;
  351. var max = n - 1;
  352. var min = 0;
  353. while (max - min > 1) {
  354. var k = Math.round((max + min) / 2);
  355. if (xdata[k] > xnew[j]) {
  356. max = k;
  357. } else {
  358. min = k;
  359. }
  360. }
  361. //found point one to the left and one to the right of generated new point
  362. var h = (xdata[max] - xdata[min]);
  363. if (h == 0) {
  364. //similar to above two points from original x data need some space between them
  365. return [];
  366. }
  367. var a = (xdata[max] - xnew[j]) / h;
  368. var b = (xnew[j] - xdata[min]) / h;
  369. ynew[j] = a * ydata[min] + b * ydata[max] + ((a * a * a - a) * y2[min] + (b * b * b - b) * y2[max]) * (h * h) / 6;
  370. result.push(xnew[j]);
  371. result.push(ynew[j]);
  372. }
  373. return result;
  374. }
  375. function hasInvalidParameters(curvedLinesOptions) {
  376. if (typeof curvedLinesOptions.fit != 'undefined' ||
  377. typeof curvedLinesOptions.curvePointFactor != 'undefined' ||
  378. typeof curvedLinesOptions.fitPointDist != 'undefined') {
  379. throw new Error("CurvedLines detected illegal parameters. The CurvedLines API changed with version 1.0.0 please check the options object.");
  380. return true;
  381. }
  382. return false;
  383. }
  384. }//end init
  385. $.plot.plugins.push({
  386. init : init,
  387. options : options,
  388. name : 'curvedLines',
  389. version : '1.1.1'
  390. });
  391. })(jQuery);