jquery.sparkline.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. /**
  2. *
  3. * jquery.sparkline.js
  4. *
  5. * v1.5.1
  6. * (c) Splunk, Inc
  7. * Contact: Gareth Watts (gareth@splunk.com)
  8. * http://omnipotent.net/jquery.sparkline/
  9. *
  10. * Generates inline sparkline charts from data supplied either to the method
  11. * or inline in HTML
  12. *
  13. * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag
  14. * (Firefox 2.0+, Safari, Opera, etc)
  15. *
  16. * License: New BSD License
  17. *
  18. * Copyright (c) 2010, Splunk Inc.
  19. * All rights reserved.
  20. *
  21. * Redistribution and use in source and binary forms, with or without modification,
  22. * are permitted provided that the following conditions are met:
  23. *
  24. * * Redistributions of source code must retain the above copyright notice,
  25. * this list of conditions and the following disclaimer.
  26. * * Redistributions in binary form must reproduce the above copyright notice,
  27. * this list of conditions and the following disclaimer in the documentation
  28. * and/or other materials provided with the distribution.
  29. * * Neither the name of Splunk Inc nor the names of its contributors may
  30. * be used to endorse or promote products derived from this software without
  31. * specific prior written permission.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
  34. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
  36. * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  38. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  39. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  40. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  41. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. *
  43. *
  44. * Usage:
  45. * $(selector).sparkline(values, options)
  46. *
  47. * If values is undefined or set to 'html' then the data values are read from the specified tag:
  48. * <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p>
  49. * $('.sparkline').sparkline();
  50. * There must be no spaces in the enclosed data set
  51. *
  52. * Otherwise values must be an array of numbers or null values
  53. * <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p>
  54. * $('#sparkline1').sparkline([1,4,6,6,8,5,3,5])
  55. * $('#sparkline2').sparkline([1,4,6,null,null,5,3,5])
  56. *
  57. * For line charts, x values can also be specified:
  58. * <p>Sparkline: <span class="sparkline">1:1,2.7:4,3.4:6,5:6,6:8,8.7:5,9:3,10:5</span></p>
  59. * $('#sparkline1').sparkline([ [1,1], [2.7,4], [3.4,6], [5,6], [6,8], [8.7,5], [9,3], [10,5] ])
  60. *
  61. * Supported options:
  62. * lineColor - Color of the line used for the chart
  63. * fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart
  64. * width - Width of the chart - Defaults to 3 times the number of values in pixels
  65. * height - Height of the chart - Defaults to the height of the containing element
  66. * chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied
  67. * chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied
  68. * chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax
  69. * chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied
  70. * chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied
  71. * composite - If true then don't erase any existing chart attached to the tag, but draw
  72. * another chart over the top - Note that width and height are ignored if an
  73. * existing chart is detected.
  74. *
  75. * There are 7 types of sparkline, selected by supplying a "type" option of 'line' (default),
  76. * 'bar', 'tristate', 'bullet', 'discrete', 'pie' or 'box'
  77. * line - Line chart. Options:
  78. * spotColor - Set to '' to not end each line in a circular spot
  79. * minSpotColor - If set, color of spot at minimum value
  80. * maxSpotColor - If set, color of spot at maximum value
  81. * spotRadius - Radius in pixels
  82. * lineWidth - Width of line in pixels
  83. * normalRangeMin
  84. * normalRangeMax - If set draws a filled horizontal bar between these two values marking the "normal"
  85. * or expected range of values
  86. * normalRangeColor - Color to use for the above bar
  87. * defaultPixelsPerValue - Defaults to 3 pixels of width for each value in the chart
  88. *
  89. * bar - Bar chart. Options:
  90. * barColor - Color of bars for postive values
  91. * negBarColor - Color of bars for negative values
  92. * zeroColor - Color of bars with zero values
  93. * nullColor - Color of bars with null values - Defaults to omitting the bar entirely
  94. * barWidth - Width of bars in pixels
  95. * colorMap - Optional mappnig of values to colors to override the *BarColor values above
  96. * can be an Array of values to control the color of individual bars
  97. * barSpacing - Gap between bars in pixels
  98. * zeroAxis - Centers the y-axis around zero if true
  99. *
  100. * tristate - Charts values of win (>0), lose (<0) or draw (=0)
  101. * posBarColor - Color of win values
  102. * negBarColor - Color of lose values
  103. * zeroBarColor - Color of draw values
  104. * barWidth - Width of bars in pixels
  105. * barSpacing - Gap between bars in pixels
  106. * colorMap - Optional mappnig of values to colors to override the *BarColor values above
  107. * can be an Array of values to control the color of individual bars
  108. *
  109. * discrete - Options:
  110. * lineHeight - Height of each line in pixels - Defaults to 30% of the graph height
  111. * thesholdValue - Values less than this value will be drawn using thresholdColor instead of lineColor
  112. * thresholdColor
  113. *
  114. * bullet - Values for bullet graphs msut be in the order: target, performance, range1, range2, range3, ...
  115. * options:
  116. * targetColor - The color of the vertical target marker
  117. * targetWidth - The width of the target marker in pixels
  118. * performanceColor - The color of the performance measure horizontal bar
  119. * rangeColors - Colors to use for each qualitative range background color
  120. *
  121. * pie - Pie chart. Options:
  122. * sliceColors - An array of colors to use for pie slices
  123. * offset - Angle in degrees to offset the first slice - Try -90 or +90
  124. *
  125. * box - Box plot. Options:
  126. * raw - Set to true to supply pre-computed plot points as values
  127. * values should be: low_outlier, low_whisker, q1, median, q3, high_whisker, high_outlier
  128. * When set to false you can supply any number of values and the box plot will
  129. * be computed for you. Default is false.
  130. * showOutliers - Set to true (default) to display outliers as circles
  131. * outlierIRQ - Interquartile range used to determine outliers. Default 1.5
  132. * boxLineColor - Outline color of the box
  133. * boxFillColor - Fill color for the box
  134. * whiskerColor - Line color used for whiskers
  135. * outlierLineColor - Outline color of outlier circles
  136. * outlierFillColor - Fill color of the outlier circles
  137. * spotRadius - Radius of outlier circles
  138. * medianColor - Line color of the median line
  139. * target - Draw a target cross hair at the supplied value (default undefined)
  140. *
  141. *
  142. *
  143. * Examples:
  144. * $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false });
  145. * $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 });
  146. * $('#tristate').sparkline([1,1,-1,1,0,0,-1], { type:'tristate' }):
  147. * $('#discrete').sparkline([1,3,4,5,5,3,4,5], { type:'discrete' });
  148. * $('#bullet').sparkline([10,12,12,9,7], { type:'bullet' });
  149. * $('#pie').sparkline([1,1,2], { type:'pie' });
  150. */
  151. (function($) {
  152. // Provide a cross-browser interface to a few simple drawing primitives
  153. $.fn.simpledraw = function(width, height, use_existing) {
  154. if (use_existing && this[0].vcanvas) return this[0].vcanvas;
  155. if (width==undefined) width=$(this).innerWidth();
  156. if (height==undefined) height=$(this).innerHeight();
  157. if ($.browser.hasCanvas) {
  158. return new vcanvas_canvas(width, height, this);
  159. } else if ($.browser.msie) {
  160. return new vcanvas_vml(width, height, this);
  161. } else {
  162. return false;
  163. }
  164. };
  165. var pending = [];
  166. $.fn.sparkline = function(uservalues, options) {
  167. var options = $.extend({
  168. type : 'line',
  169. lineColor : '#00f',
  170. fillColor : '#cdf',
  171. defaultPixelsPerValue : 3,
  172. width : 'auto',
  173. height : 'auto',
  174. composite : false
  175. }, options ? options : {});
  176. return this.each(function() {
  177. var render = function() {
  178. var values = (uservalues=='html' || uservalues==undefined) ? $(this).text().split(',') : uservalues;
  179. var width = options.width=='auto' ? values.length*options.defaultPixelsPerValue : options.width;
  180. if (options.height == 'auto') {
  181. if (!options.composite || !this.vcanvas) {
  182. // must be a better way to get the line height
  183. var tmp = document.createElement('span');
  184. tmp.innerHTML = 'a';
  185. $(this).html(tmp);
  186. height = $(tmp).innerHeight();
  187. $(tmp).remove();
  188. }
  189. } else {
  190. height = options.height;
  191. }
  192. $.fn.sparkline[options.type].call(this, values, options, width, height);
  193. }
  194. // jQuery 1.3.0 completely changed the meaning of :hidden :-/
  195. if (($(this).html() && $(this).is(':hidden')) || ($.fn.jquery < "1.3.0" && $(this).parents().is(':hidden'))) {
  196. pending.push([this, render]);
  197. } else {
  198. render.call(this);
  199. }
  200. });
  201. };
  202. $.sparkline_display_visible = function() {
  203. for (var i=pending.length-1; i>=0; i--) {
  204. var el = pending[i][0];
  205. if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
  206. pending[i][1].call(el);
  207. pending.splice(i, 1);
  208. }
  209. }
  210. };
  211. $.fn.sparkline.line = function(values, options, width, height) {
  212. var options = $.extend({
  213. spotColor : '#f80',
  214. spotRadius : 1.5,
  215. minSpotColor : '#f80',
  216. maxSpotColor : '#f80',
  217. lineWidth: 1,
  218. normalRangeMin : undefined,
  219. normalRangeMax : undefined,
  220. normalRangeColor : '#ccc',
  221. chartRangeMin : undefined,
  222. chartRangeMax : undefined,
  223. chartRangeMinX : undefined,
  224. chartRangeMaxX : undefined
  225. }, options ? options : {});
  226. var xvalues = [], yvalues = [], yminmax = [];
  227. for (i=0; i<values.length; i++) {
  228. var v = values[i];
  229. var isstr = typeof(values[i])=='string';
  230. var isarray = typeof(values[i])=='object' && values[i] instanceof Array;
  231. var sp = isstr && values[i].split(':');
  232. if (isstr && sp.length == 2) { // x:y
  233. xvalues.push(Number(sp[0]));
  234. yvalues.push(Number(sp[1]));
  235. yminmax.push(Number(sp[1]));
  236. } else if (isarray) {
  237. xvalues.push(values[i][0]);
  238. yvalues.push(values[i][1]);
  239. yminmax.push(values[i][1]);
  240. } else {
  241. xvalues.push(i);
  242. if (values[i]===null || values[i]=='null') {
  243. yvalues.push(null);
  244. } else {
  245. yvalues.push(Number(values[i]));
  246. yminmax.push(Number(values[i]));
  247. }
  248. }
  249. }
  250. if (options.xvalues) {
  251. xvalues = options.xvalues;
  252. }
  253. var maxy = Math.max.apply(Math, yminmax);
  254. var maxyval = maxy;
  255. var miny = Math.min.apply(Math, yminmax);
  256. var minyval = miny;
  257. var maxx = Math.max.apply(Math, xvalues);
  258. var maxxval = maxx;
  259. var minx = Math.min.apply(Math, xvalues);
  260. var minxval = minx;
  261. if (options.normalRangeMin!=undefined) {
  262. if (options.normalRangeMin<miny)
  263. miny = options.normalRangeMin;
  264. if (options.normalRangeMax>maxy)
  265. maxy = options.normalRangeMax;
  266. }
  267. if (options.chartRangeMin!=undefined && (options.chartRangeClip || options.chartRangeMin<miny)) {
  268. miny = options.chartRangeMin;
  269. }
  270. if (options.chartRangeMax!=undefined && (options.chartRangeClip || options.chartRangeMax>maxy)) {
  271. maxy = options.chartRangeMax;
  272. }
  273. if (options.chartRangeMinX!=undefined && (options.chartRangeClipX || options.chartRangeMinX<minx)) {
  274. minx = options.chartRangeMinX;
  275. }
  276. if (options.chartRangeMaxX!=undefined && (options.chartRangeClipX || options.chartRangeMaxX>maxx)) {
  277. maxx = options.chartRangeMaxX;
  278. }
  279. var rangex = maxx-minx == 0 ? 1 : maxx-minx;
  280. var rangey = maxy-miny == 0 ? 1 : maxy-miny;
  281. var vl = yvalues.length-1;
  282. if (vl<1) {
  283. this.innerHTML = '';
  284. return;
  285. }
  286. var target = $(this).simpledraw(width, height, options.composite);
  287. if (target) {
  288. var canvas_width = target.pixel_width;
  289. var canvas_height = target.pixel_height;
  290. var canvas_top = 0;
  291. var canvas_left = 0;
  292. if (options.spotRadius && (canvas_width < (options.spotRadius*4) || canvas_height < (options.spotRadius*4))) {
  293. options.spotRadius = 0;
  294. }
  295. if (options.spotRadius) {
  296. // adjust the canvas size as required so that spots will fit
  297. if (options.minSpotColor || (options.spotColor && yvalues[vl]==miny))
  298. canvas_height -= Math.ceil(options.spotRadius);
  299. if (options.maxSpotColor || (options.spotColor && yvalues[vl]==maxy)) {
  300. canvas_height -= Math.ceil(options.spotRadius);
  301. canvas_top += Math.ceil(options.spotRadius);
  302. }
  303. if (options.minSpotColor || options.maxSpotColor && (yvalues[0]==miny || yvalues[0]==maxy)) {
  304. canvas_left += Math.ceil(options.spotRadius);
  305. canvas_width -= Math.ceil(options.spotRadius);
  306. }
  307. if (options.spotColor || (options.minSpotColor || options.maxSpotColor && (yvalues[vl]==miny||yvalues[vl]==maxy)))
  308. canvas_width -= Math.ceil(options.spotRadius);
  309. }
  310. canvas_height--;
  311. if (options.normalRangeMin!=undefined) {
  312. var ytop = canvas_top+Math.round(canvas_height-(canvas_height*((options.normalRangeMax-miny)/rangey)));
  313. var height = Math.round((canvas_height*(options.normalRangeMax-options.normalRangeMin))/rangey);
  314. target.drawRect(canvas_left, ytop, canvas_width, height, undefined, options.normalRangeColor);
  315. }
  316. var path = [];
  317. var paths = [path];
  318. for(var i=0, vlen=yvalues.length; i<vlen; i++) {
  319. var x=xvalues[i], y=yvalues[i];
  320. if (y===null) {
  321. if (i) {
  322. if (yvalues[i-1]!==null) {
  323. path = [];
  324. paths.push(path);
  325. }
  326. }
  327. } else {
  328. if (y < miny) y=miny;
  329. if (y > maxy) y=maxy;
  330. if (!path.length) {
  331. // previous value was null
  332. path.push([canvas_left+Math.round((x-minx)*(canvas_width/rangex)), canvas_top+canvas_height]);
  333. }
  334. path.push([canvas_left+Math.round((x-minx)*(canvas_width/rangex)), canvas_top+Math.round(canvas_height-(canvas_height*((y-miny)/rangey)))]);
  335. }
  336. }
  337. for(var i=0, plen=paths.length; i<plen; i++) {
  338. path = paths[i];
  339. if (!path.length)
  340. continue; // last value was null
  341. if (options.fillColor) {
  342. path.push([path[path.length-1][0], canvas_top+canvas_height-1]);
  343. target.drawShape(path, undefined, options.fillColor);
  344. path.pop();
  345. }
  346. // if there's only a single point in this path, then we want to display it as a vertical line
  347. // which means we keep path[0] as is
  348. if (path.length>2) {
  349. // else we want the first value
  350. path[0] = [ path[0][0], path[1][1] ];
  351. }
  352. target.drawShape(path, options.lineColor, undefined, options.lineWidth);
  353. }
  354. if (options.spotRadius && options.spotColor) {
  355. target.drawCircle(canvas_left+Math.round(xvalues[xvalues.length-1]*(canvas_width/rangex)), canvas_top+Math.round(canvas_height-(canvas_height*((yvalues[vl]-miny)/rangey))), options.spotRadius, undefined, options.spotColor);
  356. }
  357. if (maxy!=minyval) {
  358. if (options.spotRadius && options.minSpotColor) {
  359. var x = xvalues[yvalues.indexOf(minyval)];
  360. target.drawCircle(canvas_left+Math.round((x-minx)*(canvas_width/rangex)), canvas_top+Math.round(canvas_height-(canvas_height*((minyval-miny)/rangey))), options.spotRadius, undefined, options.minSpotColor);
  361. }
  362. if (options.spotRadius && options.maxSpotColor) {
  363. var x = xvalues[yvalues.indexOf(maxyval)];
  364. target.drawCircle(canvas_left+Math.round((x-minx)*(canvas_width/rangex)), canvas_top+Math.round(canvas_height-(canvas_height*((maxyval-miny)/rangey))), options.spotRadius, undefined, options.maxSpotColor);
  365. }
  366. }
  367. } else {
  368. // Remove the tag contents if sparklines aren't supported
  369. this.innerHTML = '';
  370. }
  371. };
  372. $.fn.sparkline.bar = function(values, options, width, height) {
  373. var options = $.extend({
  374. type : 'bar',
  375. barColor : '#00f',
  376. negBarColor : '#f44',
  377. zeroColor: undefined,
  378. nullColor: undefined,
  379. zeroAxis : undefined,
  380. barWidth : 4,
  381. barSpacing : 1,
  382. chartRangeMax: undefined,
  383. chartRangeMin: undefined,
  384. chartRangeClip: false,
  385. colorMap : undefined
  386. }, options ? options : {});
  387. var width = (values.length * options.barWidth) + ((values.length-1) * options.barSpacing);
  388. var num_values = [];
  389. for(var i=0, vlen=values.length; i<vlen; i++) {
  390. if (values[i]=='null' || values[i]===null) {
  391. values[i] = null;
  392. } else {
  393. values[i] = Number(values[i]);
  394. num_values.push(Number(values[i]));
  395. }
  396. }
  397. var max = Math.max.apply(Math, num_values);
  398. var min = Math.min.apply(Math, num_values);
  399. if (options.chartRangeMin!=undefined && (options.chartRangeClip || options.chartRangeMin<min)) {
  400. min = options.chartRangeMin;
  401. }
  402. if (options.chartRangeMax!=undefined && (options.chartRangeClip || options.chartRangeMax>max)) {
  403. max = options.chartRangeMax;
  404. }
  405. if (options.zeroAxis == undefined) options.zeroAxis = min<0;
  406. var range = max-min == 0 ? 1 : max-min;
  407. if ($.isArray(options.colorMap)) {
  408. var colorMapByIndex = options.colorMap;
  409. var colorMapByValue = null;
  410. } else {
  411. var colorMapByIndex = null;
  412. var colorMapByValue = options.colorMap;
  413. }
  414. var target = $(this).simpledraw(width, height, options.composite);
  415. if (target) {
  416. var canvas_width = target.pixel_width;
  417. var canvas_height = target.pixel_height;
  418. var yzero = min<0 && options.zeroAxis ? canvas_height-Math.round(canvas_height * (Math.abs(min)/range))-1 : canvas_height-1;
  419. for(var i=0, vlen=values.length; i<vlen; i++) {
  420. var x = i*(options.barWidth+options.barSpacing);
  421. var val = values[i];
  422. if (val===null) {
  423. if (options.nullColor) {
  424. color = options.nullColor;
  425. val = (options.zeroAxis && min<0) ? 0 : min;
  426. var height = 1;
  427. var y = (options.zeroAxis && min<0) ? yzero : canvas_height - height;
  428. } else {
  429. continue;
  430. }
  431. } else {
  432. if (val < min) val=min;
  433. if (val > max) val=max;
  434. var color = (val < 0) ? options.negBarColor : options.barColor;
  435. if (options.zeroAxis && min<0) {
  436. var height = Math.round(canvas_height*((Math.abs(val)/range)))+1;
  437. var y = (val < 0) ? yzero : yzero-height;
  438. } else {
  439. var height = Math.round(canvas_height*((val-min)/range))+1;
  440. var y = canvas_height-height;
  441. }
  442. if (val==0 && options.zeroColor!=undefined) {
  443. color = options.zeroColor;
  444. }
  445. if (colorMapByValue && colorMapByValue[val]) {
  446. color = colorMapByValue[val];
  447. } else if (colorMapByIndex && colorMapByIndex.length>i) {
  448. color = colorMapByIndex[i];
  449. }
  450. if (color===null) {
  451. continue;
  452. }
  453. }
  454. target.drawRect(x, y, options.barWidth-1, height-1, color, color);
  455. }
  456. } else {
  457. // Remove the tag contents if sparklines aren't supported
  458. this.innerHTML = '';
  459. }
  460. };
  461. $.fn.sparkline.tristate = function(values, options, width, height) {
  462. values = $.map(values, Number);
  463. var options = $.extend({
  464. barWidth : 4,
  465. barSpacing : 1,
  466. posBarColor: '#6f6',
  467. negBarColor : '#f44',
  468. zeroBarColor : '#999',
  469. colorMap : {}
  470. }, options);
  471. var width = (values.length * options.barWidth) + ((values.length-1) * options.barSpacing);
  472. if ($.isArray(options.colorMap)) {
  473. var colorMapByIndex = options.colorMap;
  474. var colorMapByValue = null;
  475. } else {
  476. var colorMapByIndex = null;
  477. var colorMapByValue = options.colorMap;
  478. }
  479. var target = $(this).simpledraw(width, height, options.composite);
  480. if (target) {
  481. var canvas_width = target.pixel_width;
  482. var canvas_height = target.pixel_height;
  483. var half_height = Math.round(canvas_height/2);
  484. for(var i=0, vlen=values.length; i<vlen; i++) {
  485. var x = i*(options.barWidth+options.barSpacing);
  486. if (values[i] < 0) {
  487. var y = half_height;
  488. var height = half_height-1;
  489. var color = options.negBarColor;
  490. } else if (values[i] > 0) {
  491. var y = 0;
  492. var height = half_height-1;
  493. var color = options.posBarColor;
  494. } else {
  495. var y = half_height-1;
  496. var height = 2;
  497. var color = options.zeroBarColor;
  498. }
  499. if (colorMapByValue && colorMapByValue[values[i]]) {
  500. color = colorMapByValue[values[i]];
  501. } else if (colorMapByIndex && colorMapByIndex.length>i) {
  502. color = colorMapByIndex[i];
  503. }
  504. if (color===null) {
  505. continue;
  506. }
  507. target.drawRect(x, y, options.barWidth-1, height-1, color, color);
  508. }
  509. } else {
  510. // Remove the tag contents if sparklines aren't supported
  511. this.innerHTML = '';
  512. }
  513. };
  514. $.fn.sparkline.discrete = function(values, options, width, height) {
  515. values = $.map(values, Number);
  516. var options = $.extend({
  517. lineHeight: 'auto',
  518. thresholdColor: undefined,
  519. thresholdValue : 0,
  520. chartRangeMax: undefined,
  521. chartRangeMin: undefined,
  522. chartRangeClip: false
  523. }, options);
  524. width = options.width=='auto' ? values.length*2 : width;
  525. var interval = Math.floor(width / values.length);
  526. var target = $(this).simpledraw(width, height, options.composite);
  527. if (target) {
  528. var canvas_width = target.pixel_width;
  529. var canvas_height = target.pixel_height;
  530. var line_height = options.lineHeight == 'auto' ? Math.round(canvas_height * 0.3) : options.lineHeight;
  531. var pheight = canvas_height - line_height;
  532. var min = Math.min.apply(Math, values);
  533. var max = Math.max.apply(Math, values);
  534. if (options.chartRangeMin!=undefined && (options.chartRangeClip || options.chartRangeMin<min)) {
  535. min = options.chartRangeMin;
  536. }
  537. if (options.chartRangeMax!=undefined && (options.chartRangeClip || options.chartRangeMax>max)) {
  538. max = options.chartRangeMax;
  539. }
  540. var range = max-min;
  541. for(var i=0, vlen=values.length; i<vlen; i++) {
  542. var val = values[i];
  543. if (val < min) val=min;
  544. if (val > max) val=max;
  545. var x = (i*interval);
  546. var ytop = Math.round(pheight-pheight*((val-min)/range));
  547. target.drawLine(x, ytop, x, ytop+line_height, (options.thresholdColor && val < options.thresholdValue) ? options.thresholdColor : options.lineColor);
  548. }
  549. } else {
  550. // Remove the tag contents if sparklines aren't supported
  551. this.innerHTML = '';
  552. }
  553. };
  554. $.fn.sparkline.bullet = function(values, options, width, height) {
  555. values = $.map(values, Number);
  556. // target, performance, range1, range2, range3
  557. var options = $.extend({
  558. targetColor : 'red',
  559. targetWidth : 3, // width of the target bar in pixels
  560. performanceColor : 'blue',
  561. rangeColors : ['#D3DAFE', '#A8B6FF', '#7F94FF' ],
  562. base : undefined // set this to a number to change the base start number
  563. }, options);
  564. width = options.width=='auto' ? '4.0em' : width;
  565. var target = $(this).simpledraw(width, height, options.composite);
  566. if (target && values.length>1) {
  567. var canvas_width = target.pixel_width-Math.ceil(options.targetWidth/2);
  568. var canvas_height = target.pixel_height;
  569. var min = Math.min.apply(Math, values);
  570. var max = Math.max.apply(Math, values);
  571. if (options.base == undefined) {
  572. var min = min < 0 ? min : 0;
  573. } else {
  574. min = options.base;
  575. }
  576. var range = max-min;
  577. // draw range values
  578. for(i=2, vlen=values.length; i<vlen; i++) {
  579. var rangeval = parseInt(values[i]);
  580. var rangewidth = Math.round(canvas_width*((rangeval-min)/range));
  581. target.drawRect(0, 0, rangewidth-1, canvas_height-1, options.rangeColors[i-2], options.rangeColors[i-2]);
  582. }
  583. // draw the performance bar
  584. var perfval = parseInt(values[1]);
  585. var perfwidth = Math.round(canvas_width*((perfval-min)/range));
  586. target.drawRect(0, Math.round(canvas_height*0.3), perfwidth-1, Math.round(canvas_height*0.4)-1, options.performanceColor, options.performanceColor);
  587. // draw the target linej
  588. var targetval = parseInt(values[0]);
  589. var x = Math.round(canvas_width*((targetval-min)/range)-(options.targetWidth/2));
  590. var targettop = Math.round(canvas_height*0.10);
  591. var targetheight = canvas_height-(targettop*2);
  592. target.drawRect(x, targettop, options.targetWidth-1, targetheight-1, options.targetColor, options.targetColor);
  593. } else {
  594. // Remove the tag contents if sparklines aren't supported
  595. this.innerHTML = '';
  596. }
  597. };
  598. $.fn.sparkline.pie = function(values, options, width, height) {
  599. values = $.map(values, Number);
  600. var options = $.extend({
  601. sliceColors : ['#f00', '#0f0', '#00f']
  602. }, options);
  603. width = options.width=='auto' ? height : width;
  604. var target = $(this).simpledraw(width, height, options.composite);
  605. if (target && values.length>1) {
  606. var canvas_width = target.pixel_width;
  607. var canvas_height = target.pixel_height;
  608. var radius = Math.floor(Math.min(canvas_width, canvas_height)/2);
  609. var total = 0;
  610. for(var i=0, vlen=values.length; i<vlen; i++)
  611. total += values[i];
  612. var next = 0;
  613. if (options.offset) {
  614. next += (2*Math.PI)*(options.offset/360);
  615. }
  616. var circle = 2*Math.PI;
  617. for(var i=0, vlen=values.length; i<vlen; i++) {
  618. var start = next;
  619. var end = next;
  620. if (total > 0) { // avoid divide by zero
  621. end = next + (circle*(values[i]/total));
  622. }
  623. target.drawPieSlice(radius, radius, radius, start, end, undefined, options.sliceColors[i % options.sliceColors.length]);
  624. next = end;
  625. }
  626. }
  627. };
  628. function quartile(values, q) {
  629. if (q==2) {
  630. var vl2 = Math.floor(values.length/2);
  631. return values.length % 2 ? values[vl2] : (values[vl2]+values[vl2+1])/2;
  632. } else {
  633. var vl4 = Math.floor(values.length/4);
  634. return values.length % 2 ? (values[vl4*q]+values[vl4*q+1])/2 : values[vl4*q];
  635. }
  636. };
  637. $.fn.sparkline.box = function(values, options, width, height) {
  638. values = $.map(values, Number);
  639. var options = $.extend({
  640. raw: false,
  641. boxLineColor: 'black',
  642. boxFillColor: '#cdf',
  643. whiskerColor: 'black',
  644. outlierLineColor: '#333',
  645. outlierFillColor: 'white',
  646. medianColor: 'red',
  647. showOutliers: true,
  648. outlierIQR: 1.5,
  649. spotRadius: 1.5,
  650. target: undefined,
  651. targetColor: '#4a2',
  652. chartRangeMax: undefined,
  653. chartRangeMin: undefined
  654. }, options);
  655. width = options.width=='auto' ? '4.0em' : width;
  656. minvalue = options.chartRangeMin==undefined ? Math.min.apply(Math, values) : options.chartRangeMin;
  657. maxvalue = options.chartRangeMax==undefined ? Math.max.apply(Math, values) : options.chartRangeMax;
  658. var target = $(this).simpledraw(width, height, options.composite);
  659. if (target && values.length>1) {
  660. var canvas_width = target.pixel_width;
  661. var canvas_height = target.pixel_height;
  662. if (options.raw) {
  663. if (options.showOutliers && values.length>5) {
  664. var loutlier=values[0], lwhisker=values[1], q1=values[2], q2=values[3], q3=values[4], rwhisker=values[5], routlier=values[6];
  665. } else {
  666. var lwhisker=values[0], q1=values[1], q2=values[2], q3=values[3], rwhisker=values[4];
  667. }
  668. } else {
  669. values.sort(function(a, b) { return a-b; });
  670. var q1 = quartile(values, 1);
  671. var q2 = quartile(values, 2);
  672. var q3 = quartile(values, 3);
  673. var iqr = q3-q1;
  674. if (options.showOutliers) {
  675. var lwhisker=undefined, rwhisker=undefined;
  676. for(var i=0, vlen=values.length; i<vlen; i++) {
  677. if (lwhisker==undefined && values[i] > q1-(iqr*options.outlierIQR))
  678. lwhisker = values[i];
  679. if (values[i] < q3+(iqr*options.outlierIQR))
  680. rwhisker = values[i];
  681. }
  682. var loutlier = values[0];
  683. var routlier = values[values.length-1];
  684. } else {
  685. var lwhisker = values[0];
  686. var rwhisker = values[values.length-1];
  687. }
  688. }
  689. var unitsize = canvas_width / (maxvalue-minvalue+1);
  690. var canvas_left = 0;
  691. if (options.showOutliers) {
  692. canvas_left = Math.ceil(options.spotRadius);
  693. canvas_width -= 2*Math.ceil(options.spotRadius);
  694. var unitsize = canvas_width / (maxvalue-minvalue+1);
  695. if (loutlier < lwhisker)
  696. target.drawCircle((loutlier-minvalue)*unitsize+canvas_left, canvas_height/2, options.spotRadius, options.outlierLineColor, options.outlierFillColor);
  697. if (routlier > rwhisker)
  698. target.drawCircle((routlier-minvalue)*unitsize+canvas_left, canvas_height/2, options.spotRadius, options.outlierLineColor, options.outlierFillColor);
  699. }
  700. // box
  701. target.drawRect(
  702. Math.round((q1-minvalue)*unitsize+canvas_left),
  703. Math.round(canvas_height*0.1),
  704. Math.round((q3-q1)*unitsize),
  705. Math.round(canvas_height*0.8),
  706. options.boxLineColor,
  707. options.boxFillColor);
  708. // left whisker
  709. target.drawLine(
  710. Math.round((lwhisker-minvalue)*unitsize+canvas_left),
  711. Math.round(canvas_height/2),
  712. Math.round((q1-minvalue)*unitsize+canvas_left),
  713. Math.round(canvas_height/2),
  714. options.lineColor);
  715. target.drawLine(
  716. Math.round((lwhisker-minvalue)*unitsize+canvas_left),
  717. Math.round(canvas_height/4),
  718. Math.round((lwhisker-minvalue)*unitsize+canvas_left),
  719. Math.round(canvas_height-canvas_height/4),
  720. options.whiskerColor);
  721. // right whisker
  722. target.drawLine(Math.round((rwhisker-minvalue)*unitsize+canvas_left),
  723. Math.round(canvas_height/2),
  724. Math.round((q3-minvalue)*unitsize+canvas_left),
  725. Math.round(canvas_height/2),
  726. options.lineColor);
  727. target.drawLine(
  728. Math.round((rwhisker-minvalue)*unitsize+canvas_left),
  729. Math.round(canvas_height/4),
  730. Math.round((rwhisker-minvalue)*unitsize+canvas_left),
  731. Math.round(canvas_height-canvas_height/4),
  732. options.whiskerColor);
  733. // median line
  734. target.drawLine(
  735. Math.round((q2-minvalue)*unitsize+canvas_left),
  736. Math.round(canvas_height*0.1),
  737. Math.round((q2-minvalue)*unitsize+canvas_left),
  738. Math.round(canvas_height*0.9),
  739. options.medianColor);
  740. if (options.target) {
  741. var size = Math.ceil(options.spotRadius);
  742. target.drawLine(
  743. Math.round((options.target-minvalue)*unitsize+canvas_left),
  744. Math.round((canvas_height/2)-size),
  745. Math.round((options.target-minvalue)*unitsize+canvas_left),
  746. Math.round((canvas_height/2)+size),
  747. options.targetColor);
  748. target.drawLine(
  749. Math.round((options.target-minvalue)*unitsize+canvas_left-size),
  750. Math.round(canvas_height/2),
  751. Math.round((options.target-minvalue)*unitsize+canvas_left+size),
  752. Math.round(canvas_height/2),
  753. options.targetColor);
  754. }
  755. } else {
  756. // Remove the tag contents if sparklines aren't supported
  757. this.innerHTML = '';
  758. }
  759. };
  760. // IE doesn't provide an indexOf method for arrays :-(
  761. if (!Array.prototype.indexOf) {
  762. Array.prototype.indexOf = function(entry) {
  763. for(var i=0, vlen=this.length; i<vlen; i++) {
  764. if (this[i] == entry)
  765. return i;
  766. }
  767. return -1;
  768. }
  769. }
  770. // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
  771. // This is accessible as $(foo).simpledraw()
  772. if ($.browser.msie && !document.namespaces['v']) {
  773. document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
  774. }
  775. if ($.browser.hasCanvas == undefined) {
  776. var t = document.createElement('canvas');
  777. $.browser.hasCanvas = t.getContext!=undefined;
  778. }
  779. var vcanvas_base = function(width, height, target) {
  780. };
  781. vcanvas_base.prototype = {
  782. init : function(width, height, target) {
  783. this.width = width;
  784. this.height = height;
  785. this.target = target;
  786. if (target[0]) target=target[0];
  787. target.vcanvas = this;
  788. },
  789. drawShape : function(path, lineColor, fillColor, lineWidth) {
  790. alert('drawShape not implemented');
  791. },
  792. drawLine : function(x1, y1, x2, y2, lineColor, lineWidth) {
  793. return this.drawShape([ [x1,y1], [x2,y2] ], lineColor, lineWidth);
  794. },
  795. drawCircle : function(x, y, radius, lineColor, fillColor) {
  796. alert('drawCircle not implemented');
  797. },
  798. drawPieSlice : function(x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  799. alert('drawPieSlice not implemented');
  800. },
  801. drawRect : function(x, y, width, height, lineColor, fillColor) {
  802. alert('drawRect not implemented');
  803. },
  804. getElement : function() {
  805. return this.canvas;
  806. },
  807. _insert : function(el, target) {
  808. $(target).html(el);
  809. }
  810. };
  811. var vcanvas_canvas = function(width, height, target) {
  812. return this.init(width, height, target);
  813. };
  814. vcanvas_canvas.prototype = $.extend(new vcanvas_base, {
  815. _super : vcanvas_base.prototype,
  816. init : function(width, height, target) {
  817. this._super.init(width, height, target);
  818. this.canvas = document.createElement('canvas');
  819. if (target[0]) target=target[0];
  820. target.vcanvas = this;
  821. $(this.canvas).css({ display:'inline-block', width:width, height:height, verticalAlign:'top' });
  822. this._insert(this.canvas, target);
  823. this.pixel_height = $(this.canvas).height();
  824. this.pixel_width = $(this.canvas).width();
  825. this.canvas.width = this.pixel_width;
  826. this.canvas.height = this.pixel_height;
  827. $(this.canvas).css({width: this.pixel_width, height: this.pixel_height});
  828. },
  829. _getContext : function(lineColor, fillColor, lineWidth) {
  830. var context = this.canvas.getContext('2d');
  831. if (lineColor != undefined)
  832. context.strokeStyle = lineColor;
  833. context.lineWidth = lineWidth==undefined ? 1 : lineWidth;
  834. if (fillColor != undefined)
  835. context.fillStyle = fillColor;
  836. return context;
  837. },
  838. drawShape : function(path, lineColor, fillColor, lineWidth) {
  839. var context = this._getContext(lineColor, fillColor, lineWidth);
  840. context.beginPath();
  841. context.moveTo(path[0][0]+0.5, path[0][1]+0.5);
  842. for(var i=1, plen=path.length; i<plen; i++) {
  843. context.lineTo(path[i][0]+0.5, path[i][1]+0.5); // the 0.5 offset gives us crisp pixel-width lines
  844. }
  845. if (lineColor != undefined) {
  846. context.stroke();
  847. }
  848. if (fillColor != undefined) {
  849. context.fill();
  850. }
  851. },
  852. drawCircle : function(x, y, radius, lineColor, fillColor) {
  853. var context = this._getContext(lineColor, fillColor);
  854. context.beginPath();
  855. context.arc(x, y, radius, 0, 2*Math.PI, false);
  856. if (lineColor != undefined) {
  857. context.stroke();
  858. }
  859. if (fillColor != undefined) {
  860. context.fill();
  861. }
  862. },
  863. drawPieSlice : function(x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  864. var context = this._getContext(lineColor, fillColor);
  865. context.beginPath();
  866. context.moveTo(x, y);
  867. context.arc(x, y, radius, startAngle, endAngle, false);
  868. context.lineTo(x, y);
  869. context.closePath();
  870. if (lineColor != undefined) {
  871. context.stroke();
  872. }
  873. if (fillColor) {
  874. context.fill();
  875. }
  876. },
  877. drawRect : function(x, y, width, height, lineColor, fillColor) {
  878. return this.drawShape([ [x,y], [x+width, y], [x+width, y+height], [x, y+height], [x, y] ], lineColor, fillColor);
  879. }
  880. });
  881. var vcanvas_vml = function(width, height, target) {
  882. return this.init(width, height, target);
  883. };
  884. vcanvas_vml.prototype = $.extend(new vcanvas_base, {
  885. _super : vcanvas_base.prototype,
  886. init : function(width, height, target) {
  887. this._super.init(width, height, target);
  888. if (target[0]) target=target[0];
  889. target.vcanvas = this;
  890. this.canvas = document.createElement('span');
  891. $(this.canvas).css({ display:'inline-block', position: 'relative', overflow:'hidden', width:width, height:height, margin:'0px', padding:'0px', verticalAlign: 'top'});
  892. this._insert(this.canvas, target);
  893. this.pixel_height = $(this.canvas).height();
  894. this.pixel_width = $(this.canvas).width();
  895. this.canvas.width = this.pixel_width;
  896. this.canvas.height = this.pixel_height;;
  897. var groupel = '<v:group coordorigin="0 0" coordsize="'+this.pixel_width+' '+this.pixel_height+'"'
  898. +' style="position:absolute;top:0;left:0;width:'+this.pixel_width+'px;height='+this.pixel_height+'px;"></v:group>';
  899. this.canvas.insertAdjacentHTML('beforeEnd', groupel);
  900. this.group = $(this.canvas).children()[0];
  901. },
  902. drawShape : function(path, lineColor, fillColor, lineWidth) {
  903. var vpath = [];
  904. for(var i=0, plen=path.length; i<plen; i++) {
  905. vpath[i] = ''+(path[i][0])+','+(path[i][1]);
  906. }
  907. var initial = vpath.splice(0,1);
  908. lineWidth = lineWidth == undefined ? 1 : lineWidth;
  909. var stroke = lineColor == undefined ? ' stroked="false" ' : ' strokeWeight="'+lineWidth+'" strokeColor="'+lineColor+'" ';
  910. var fill = fillColor == undefined ? ' filled="false"' : ' fillColor="'+fillColor+'" filled="true" ';
  911. var closed = vpath[0] == vpath[vpath.length-1] ? 'x ' : '';
  912. var vel = '<v:shape coordorigin="0 0" coordsize="'+this.pixel_width+' '+this.pixel_height+'" '
  913. + stroke
  914. + fill
  915. +' style="position:absolute;left:0px;top:0px;height:'+this.pixel_height+'px;width:'+this.pixel_width+'px;padding:0px;margin:0px;" '
  916. +' path="m '+initial+' l '+vpath.join(', ')+' '+closed+'e">'
  917. +' </v:shape>';
  918. this.group.insertAdjacentHTML('beforeEnd', vel);
  919. },
  920. drawCircle : function(x, y, radius, lineColor, fillColor) {
  921. x -= radius+1;
  922. y -= radius+1;
  923. var stroke = lineColor == undefined ? ' stroked="false" ' : ' strokeWeight="1" strokeColor="'+lineColor+'" ';
  924. var fill = fillColor == undefined ? ' filled="false"' : ' fillColor="'+fillColor+'" filled="true" ';
  925. var vel = '<v:oval '
  926. + stroke
  927. + fill
  928. +' style="position:absolute;top:'+y+'px; left:'+x+'px; width:'+(radius*2)+'px; height:'+(radius*2)+'px"></v:oval>';
  929. this.group.insertAdjacentHTML('beforeEnd', vel);
  930. },
  931. drawPieSlice : function(x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  932. if (startAngle == endAngle) {
  933. return; // VML seems to have problem when start angle equals end angle.
  934. }
  935. if ((endAngle - startAngle) == (2*Math.PI)) {
  936. startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0
  937. endAngle = (2*Math.PI);
  938. }
  939. var startx = x + Math.round(Math.cos(startAngle) * radius);
  940. var starty = y + Math.round(Math.sin(startAngle) * radius);
  941. var endx = x + Math.round(Math.cos(endAngle) * radius);
  942. var endy = y + Math.round(Math.sin(endAngle) * radius);
  943. // Prevent very small slices from being mistaken as a whole pie
  944. if (startx==endx && starty==endy && (endAngle-startAngle) < Math.PI)
  945. return;
  946. var vpath = [ x-radius, y-radius, x+radius, y+radius, startx, starty, endx, endy ];
  947. var stroke = lineColor == undefined ? ' stroked="false" ' : ' strokeWeight="1" strokeColor="'+lineColor+'" ';
  948. var fill = fillColor == undefined ? ' filled="false"' : ' fillColor="'+fillColor+'" filled="true" ';
  949. var vel = '<v:shape coordorigin="0 0" coordsize="'+this.pixel_width+' '+this.pixel_height+'" '
  950. + stroke
  951. + fill
  952. +' style="position:absolute;left:0px;top:0px;height:'+this.pixel_height+'px;width:'+this.pixel_width+'px;padding:0px;margin:0px;" '
  953. +' path="m '+x+','+y+' wa '+vpath.join(', ')+' x e">'
  954. +' </v:shape>';
  955. this.group.insertAdjacentHTML('beforeEnd', vel);
  956. },
  957. drawRect : function(x, y, width, height, lineColor, fillColor) {
  958. return this.drawShape( [ [x, y], [x, y+height], [x+width, y+height], [x+width, y], [x, y] ], lineColor, fillColor);
  959. }
  960. });
  961. })(jQuery);