jquery.flot.js 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766
  1. /* Javascript plotting library for jQuery, version 1.0.3.
  2. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3. Licensed under the MIT license.
  4. */
  5. // the actual Flot code
  6. (function($) {
  7. "use strict";
  8. var Canvas = window.Flot.Canvas;
  9. function defaultTickGenerator(axis) {
  10. var ticks = [],
  11. start = $.plot.saturated.saturate($.plot.saturated.floorInBase(axis.min, axis.tickSize)),
  12. i = 0,
  13. v = Number.NaN,
  14. prev;
  15. if (start === -Number.MAX_VALUE) {
  16. ticks.push(start);
  17. start = $.plot.saturated.floorInBase(axis.min + axis.tickSize, axis.tickSize);
  18. }
  19. do {
  20. prev = v;
  21. //v = start + i * axis.tickSize;
  22. v = $.plot.saturated.multiplyAdd(axis.tickSize, i, start);
  23. ticks.push(v);
  24. ++i;
  25. } while (v < axis.max && v !== prev);
  26. return ticks;
  27. }
  28. function defaultTickFormatter(value, axis, precision) {
  29. var oldTickDecimals = axis.tickDecimals,
  30. expPosition = ("" + value).indexOf("e");
  31. if (expPosition !== -1) {
  32. return expRepTickFormatter(value, axis, precision);
  33. }
  34. if (precision > 0) {
  35. axis.tickDecimals = precision;
  36. }
  37. var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1,
  38. formatted = "" + Math.round(value * factor) / factor;
  39. // If tickDecimals was specified, ensure that we have exactly that
  40. // much precision; otherwise default to the value's own precision.
  41. if (axis.tickDecimals != null) {
  42. var decimal = formatted.indexOf("."),
  43. decimalPrecision = decimal === -1 ? 0 : formatted.length - decimal - 1;
  44. if (decimalPrecision < axis.tickDecimals) {
  45. var decimals = ("" + factor).substr(1, axis.tickDecimals - decimalPrecision);
  46. formatted = (decimalPrecision ? formatted : formatted + ".") + decimals;
  47. }
  48. }
  49. axis.tickDecimals = oldTickDecimals;
  50. return formatted;
  51. };
  52. function expRepTickFormatter(value, axis, precision) {
  53. var expPosition = ("" + value).indexOf("e"),
  54. exponentValue = parseInt(("" + value).substr(expPosition + 1)),
  55. tenExponent = expPosition !== -1 ? exponentValue : (value > 0 ? Math.floor(Math.log(value) / Math.LN10) : 0),
  56. roundWith = Math.pow(10, tenExponent),
  57. x = value / roundWith;
  58. if (precision) {
  59. var updatedPrecision = recomputePrecision(value, precision);
  60. return (value / roundWith).toFixed(updatedPrecision) + 'e' + tenExponent;
  61. }
  62. if (axis.tickDecimals > 0) {
  63. return x.toFixed(recomputePrecision(value, axis.tickDecimals)) + 'e' + tenExponent;
  64. }
  65. return x.toFixed() + 'e' + tenExponent;
  66. }
  67. function recomputePrecision(num, precision) {
  68. //for numbers close to zero, the precision from flot will be a big number
  69. //while for big numbers, the precision will be negative
  70. var log10Value = Math.log(Math.abs(num)) * Math.LOG10E,
  71. newPrecision = Math.abs(log10Value + precision);
  72. return newPrecision <= 20 ? Math.floor(newPrecision) : 20;
  73. }
  74. ///////////////////////////////////////////////////////////////////////////
  75. // The top-level container for the entire plot.
  76. function Plot(placeholder, data_, options_, plugins) {
  77. // data is on the form:
  78. // [ series1, series2 ... ]
  79. // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
  80. // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
  81. var series = [],
  82. options = {
  83. // the color theme used for graphs
  84. colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
  85. xaxis: {
  86. show: null, // null = auto-detect, true = always, false = never
  87. position: "bottom", // or "top"
  88. mode: null, // null or "time"
  89. font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
  90. color: null, // base color, labels, ticks
  91. tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
  92. transform: null, // null or f: number -> number to transform axis
  93. inverseTransform: null, // if transform is set, this should be the inverse function
  94. min: null, // min. value to show, null means set automatically
  95. max: null, // max. value to show, null means set automatically
  96. autoScaleMargin: null, // margin in % to add if autoScale option is on "loose" mode,
  97. autoScale: "exact", // Available modes: "none", "loose", "exact", "sliding-window"
  98. windowSize: null, // null or number. This is the size of sliding-window.
  99. growOnly: null, // grow only, useful for smoother auto-scale, the scales will grow to accomodate data but won't shrink back.
  100. ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
  101. tickFormatter: null, // fn: number -> string
  102. showTickLabels: "major", // "none", "endpoints", "major", "all"
  103. labelWidth: null, // size of tick labels in pixels
  104. labelHeight: null,
  105. reserveSpace: null, // whether to reserve space even if axis isn't shown
  106. tickLength: null, // size in pixels of major tick marks
  107. showMinorTicks: null, // true = show minor tick marks, false = hide minor tick marks
  108. showTicks: null, // true = show tick marks, false = hide all tick marks
  109. gridLines: null, // true = show grid lines, false = hide grid lines
  110. alignTicksWithAxis: null, // axis number or null for no sync
  111. tickDecimals: null, // no. of decimals, null means auto
  112. tickSize: null, // number or [number, "unit"]
  113. minTickSize: null, // number or [number, "unit"]
  114. offset: { below: 0, above: 0 }, // the plot drawing offset. this is calculated by the flot.navigate for each axis
  115. boxPosition: { centerX: 0, centerY: 0 } //position of the axis on the corresponding axis box
  116. },
  117. yaxis: {
  118. autoScaleMargin: 0.02, // margin in % to add if autoScale option is on "loose" mode
  119. autoScale: "loose", // Available modes: "none", "loose", "exact"
  120. growOnly: null, // grow only, useful for smoother auto-scale, the scales will grow to accomodate data but won't shrink back.
  121. position: "left", // or "right"
  122. showTickLabels: "major", // "none", "endpoints", "major", "all"
  123. offset: { below: 0, above: 0 }, // the plot drawing offset. this is calculated by the flot.navigate for each axis
  124. boxPosition: { centerX: 0, centerY: 0 } //position of the axis on the corresponding axis box
  125. },
  126. xaxes: [],
  127. yaxes: [],
  128. series: {
  129. points: {
  130. show: false,
  131. radius: 3,
  132. lineWidth: 2, // in pixels
  133. fill: true,
  134. fillColor: "#ffffff",
  135. symbol: 'circle' // or callback
  136. },
  137. lines: {
  138. // we don't put in show: false so we can see
  139. // whether lines were actively disabled
  140. lineWidth: 1, // in pixels
  141. fill: false,
  142. fillColor: null,
  143. steps: false
  144. // Omit 'zero', so we can later default its value to
  145. // match that of the 'fill' option.
  146. },
  147. bars: {
  148. show: false,
  149. lineWidth: 2, // in pixels
  150. // barWidth: number or [number, absolute]
  151. // when 'absolute' is false, 'number' is relative to the minimum distance between points for the series
  152. // when 'absolute' is true, 'number' is considered to be in units of the x-axis
  153. horizontal: false,
  154. barWidth: 0.8,
  155. fill: true,
  156. fillColor: null,
  157. align: "left", // "left", "right", or "center"
  158. zero: true
  159. },
  160. shadowSize: 3,
  161. highlightColor: null
  162. },
  163. grid: {
  164. show: true,
  165. aboveData: false,
  166. color: "#545454", // primary color used for outline and labels
  167. backgroundColor: null, // null for transparent, else color
  168. borderColor: null, // set if different from the grid color
  169. tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
  170. margin: 0, // distance from the canvas edge to the grid
  171. labelMargin: 5, // in pixels
  172. axisMargin: 8, // in pixels
  173. borderWidth: 1, // in pixels
  174. minBorderMargin: null, // in pixels, null means taken from points radius
  175. markings: null, // array of ranges or fn: axes -> array of ranges
  176. markingsColor: "#f4f4f4",
  177. markingsLineWidth: 2,
  178. // interactive stuff
  179. clickable: false,
  180. hoverable: false,
  181. autoHighlight: true, // highlight in case mouse is near
  182. mouseActiveRadius: 15 // how far the mouse can be away to activate an item
  183. },
  184. interaction: {
  185. redrawOverlayInterval: 1000 / 60 // time between updates, -1 means in same flow
  186. },
  187. hooks: {}
  188. },
  189. surface = null, // the canvas for the plot itself
  190. overlay = null, // canvas for interactive stuff on top of plot
  191. eventHolder = null, // jQuery object that events should be bound to
  192. ctx = null,
  193. octx = null,
  194. xaxes = [],
  195. yaxes = [],
  196. plotOffset = {
  197. left: 0,
  198. right: 0,
  199. top: 0,
  200. bottom: 0
  201. },
  202. plotWidth = 0,
  203. plotHeight = 0,
  204. hooks = {
  205. processOptions: [],
  206. processRawData: [],
  207. processDatapoints: [],
  208. processOffset: [],
  209. setupGrid: [],
  210. adjustSeriesDataRange: [],
  211. setRange: [],
  212. drawBackground: [],
  213. drawSeries: [],
  214. drawAxis: [],
  215. draw: [],
  216. axisReserveSpace: [],
  217. bindEvents: [],
  218. drawOverlay: [],
  219. resize: [],
  220. shutdown: []
  221. },
  222. plot = this;
  223. var eventManager = {};
  224. // interactive features
  225. var redrawTimeout = null;
  226. // public functions
  227. plot.setData = setData;
  228. plot.setupGrid = setupGrid;
  229. plot.draw = draw;
  230. plot.getPlaceholder = function() {
  231. return placeholder;
  232. };
  233. plot.getCanvas = function() {
  234. return surface.element;
  235. };
  236. plot.getSurface = function() {
  237. return surface;
  238. };
  239. plot.getEventHolder = function() {
  240. return eventHolder[0];
  241. };
  242. plot.getPlotOffset = function() {
  243. return plotOffset;
  244. };
  245. plot.width = function() {
  246. return plotWidth;
  247. };
  248. plot.height = function() {
  249. return plotHeight;
  250. };
  251. plot.offset = function() {
  252. var o = eventHolder.offset();
  253. o.left += plotOffset.left;
  254. o.top += plotOffset.top;
  255. return o;
  256. };
  257. plot.getData = function() {
  258. return series;
  259. };
  260. plot.getAxes = function() {
  261. var res = {};
  262. $.each(xaxes.concat(yaxes), function(_, axis) {
  263. if (axis) {
  264. res[axis.direction + (axis.n !== 1 ? axis.n : "") + "axis"] = axis;
  265. }
  266. });
  267. return res;
  268. };
  269. plot.getXAxes = function() {
  270. return xaxes;
  271. };
  272. plot.getYAxes = function() {
  273. return yaxes;
  274. };
  275. plot.c2p = canvasToCartesianAxisCoords;
  276. plot.p2c = cartesianAxisToCanvasCoords;
  277. plot.getOptions = function() {
  278. return options;
  279. };
  280. plot.triggerRedrawOverlay = triggerRedrawOverlay;
  281. plot.pointOffset = function(point) {
  282. return {
  283. left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
  284. top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
  285. };
  286. };
  287. plot.shutdown = shutdown;
  288. plot.destroy = function() {
  289. shutdown();
  290. placeholder.removeData("plot").empty();
  291. series = [];
  292. options = null;
  293. surface = null;
  294. overlay = null;
  295. eventHolder = null;
  296. ctx = null;
  297. octx = null;
  298. xaxes = [];
  299. yaxes = [];
  300. hooks = null;
  301. plot = null;
  302. };
  303. plot.resize = function() {
  304. var width = placeholder.width(),
  305. height = placeholder.height();
  306. surface.resize(width, height);
  307. overlay.resize(width, height);
  308. executeHooks(hooks.resize, [width, height]);
  309. };
  310. plot.clearTextCache = function () {
  311. surface.clearCache();
  312. overlay.clearCache();
  313. };
  314. plot.autoScaleAxis = autoScaleAxis;
  315. plot.computeRangeForDataSeries = computeRangeForDataSeries;
  316. plot.adjustSeriesDataRange = adjustSeriesDataRange;
  317. plot.findNearbyItem = findNearbyItem;
  318. plot.findNearbyInterpolationPoint = findNearbyInterpolationPoint;
  319. plot.computeValuePrecision = computeValuePrecision;
  320. plot.computeTickSize = computeTickSize;
  321. plot.addEventHandler = addEventHandler;
  322. // public attributes
  323. plot.hooks = hooks;
  324. // initialize
  325. var MINOR_TICKS_COUNT_CONSTANT = $.plot.uiConstants.MINOR_TICKS_COUNT_CONSTANT;
  326. var TICK_LENGTH_CONSTANT = $.plot.uiConstants.TICK_LENGTH_CONSTANT;
  327. initPlugins(plot);
  328. setupCanvases();
  329. parseOptions(options_);
  330. setData(data_);
  331. setupGrid(true);
  332. draw();
  333. bindEvents();
  334. function executeHooks(hook, args) {
  335. args = [plot].concat(args);
  336. for (var i = 0; i < hook.length; ++i) {
  337. hook[i].apply(this, args);
  338. }
  339. }
  340. function initPlugins() {
  341. // References to key classes, allowing plugins to modify them
  342. var classes = {
  343. Canvas: Canvas
  344. };
  345. for (var i = 0; i < plugins.length; ++i) {
  346. var p = plugins[i];
  347. p.init(plot, classes);
  348. if (p.options) {
  349. $.extend(true, options, p.options);
  350. }
  351. }
  352. }
  353. function parseOptions(opts) {
  354. $.extend(true, options, opts);
  355. // $.extend merges arrays, rather than replacing them. When less
  356. // colors are provided than the size of the default palette, we
  357. // end up with those colors plus the remaining defaults, which is
  358. // not expected behavior; avoid it by replacing them here.
  359. if (opts && opts.colors) {
  360. options.colors = opts.colors;
  361. }
  362. if (options.xaxis.color == null) {
  363. options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  364. }
  365. if (options.yaxis.color == null) {
  366. options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  367. }
  368. if (options.xaxis.tickColor == null) {
  369. // grid.tickColor for back-compatibility
  370. options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
  371. }
  372. if (options.yaxis.tickColor == null) {
  373. // grid.tickColor for back-compatibility
  374. options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
  375. }
  376. if (options.grid.borderColor == null) {
  377. options.grid.borderColor = options.grid.color;
  378. }
  379. if (options.grid.tickColor == null) {
  380. options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  381. }
  382. // Fill in defaults for axis options, including any unspecified
  383. // font-spec fields, if a font-spec was provided.
  384. // If no x/y axis options were provided, create one of each anyway,
  385. // since the rest of the code assumes that they exist.
  386. var i, axisOptions, axisCount,
  387. fontSize = placeholder.css("font-size"),
  388. fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
  389. fontDefaults = {
  390. style: placeholder.css("font-style"),
  391. size: Math.round(0.8 * fontSizeDefault),
  392. variant: placeholder.css("font-variant"),
  393. weight: placeholder.css("font-weight"),
  394. family: placeholder.css("font-family")
  395. };
  396. axisCount = options.xaxes.length || 1;
  397. for (i = 0; i < axisCount; ++i) {
  398. axisOptions = options.xaxes[i];
  399. if (axisOptions && !axisOptions.tickColor) {
  400. axisOptions.tickColor = axisOptions.color;
  401. }
  402. axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
  403. options.xaxes[i] = axisOptions;
  404. if (axisOptions.font) {
  405. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  406. if (!axisOptions.font.color) {
  407. axisOptions.font.color = axisOptions.color;
  408. }
  409. if (!axisOptions.font.lineHeight) {
  410. axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
  411. }
  412. }
  413. }
  414. axisCount = options.yaxes.length || 1;
  415. for (i = 0; i < axisCount; ++i) {
  416. axisOptions = options.yaxes[i];
  417. if (axisOptions && !axisOptions.tickColor) {
  418. axisOptions.tickColor = axisOptions.color;
  419. }
  420. axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
  421. options.yaxes[i] = axisOptions;
  422. if (axisOptions.font) {
  423. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  424. if (!axisOptions.font.color) {
  425. axisOptions.font.color = axisOptions.color;
  426. }
  427. if (!axisOptions.font.lineHeight) {
  428. axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
  429. }
  430. }
  431. }
  432. // save options on axes for future reference
  433. for (i = 0; i < options.xaxes.length; ++i) {
  434. getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
  435. }
  436. for (i = 0; i < options.yaxes.length; ++i) {
  437. getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
  438. }
  439. //process boxPosition options used for axis.box size
  440. $.each(allAxes(), function(_, axis) {
  441. axis.boxPosition = axis.options.boxPosition || {centerX: 0, centerY: 0};
  442. });
  443. // add hooks from options
  444. for (var n in hooks) {
  445. if (options.hooks[n] && options.hooks[n].length) {
  446. hooks[n] = hooks[n].concat(options.hooks[n]);
  447. }
  448. }
  449. executeHooks(hooks.processOptions, [options]);
  450. }
  451. function setData(d) {
  452. var oldseries = series;
  453. series = parseData(d);
  454. fillInSeriesOptions();
  455. processData(oldseries);
  456. }
  457. function parseData(d) {
  458. var res = [];
  459. for (var i = 0; i < d.length; ++i) {
  460. var s = $.extend(true, {}, options.series);
  461. if (d[i].data != null) {
  462. s.data = d[i].data; // move the data instead of deep-copy
  463. delete d[i].data;
  464. $.extend(true, s, d[i]);
  465. d[i].data = s.data;
  466. } else {
  467. s.data = d[i];
  468. }
  469. res.push(s);
  470. }
  471. return res;
  472. }
  473. function axisNumber(obj, coord) {
  474. var a = obj[coord + "axis"];
  475. if (typeof a === "object") {
  476. // if we got a real axis, extract number
  477. a = a.n;
  478. }
  479. if (typeof a !== "number") {
  480. a = 1; // default to first axis
  481. }
  482. return a;
  483. }
  484. function allAxes() {
  485. // return flat array without annoying null entries
  486. return xaxes.concat(yaxes).filter(function(a) {
  487. return a;
  488. });
  489. }
  490. // canvas to axis for cartesian axes
  491. function canvasToCartesianAxisCoords(pos) {
  492. // return an object with x/y corresponding to all used axes
  493. var res = {},
  494. i, axis;
  495. for (i = 0; i < xaxes.length; ++i) {
  496. axis = xaxes[i];
  497. if (axis && axis.used) {
  498. res["x" + axis.n] = axis.c2p(pos.left);
  499. }
  500. }
  501. for (i = 0; i < yaxes.length; ++i) {
  502. axis = yaxes[i];
  503. if (axis && axis.used) {
  504. res["y" + axis.n] = axis.c2p(pos.top);
  505. }
  506. }
  507. if (res.x1 !== undefined) {
  508. res.x = res.x1;
  509. }
  510. if (res.y1 !== undefined) {
  511. res.y = res.y1;
  512. }
  513. return res;
  514. }
  515. // axis to canvas for cartesian axes
  516. function cartesianAxisToCanvasCoords(pos) {
  517. // get canvas coords from the first pair of x/y found in pos
  518. var res = {},
  519. i, axis, key;
  520. for (i = 0; i < xaxes.length; ++i) {
  521. axis = xaxes[i];
  522. if (axis && axis.used) {
  523. key = "x" + axis.n;
  524. if (pos[key] == null && axis.n === 1) {
  525. key = "x";
  526. }
  527. if (pos[key] != null) {
  528. res.left = axis.p2c(pos[key]);
  529. break;
  530. }
  531. }
  532. }
  533. for (i = 0; i < yaxes.length; ++i) {
  534. axis = yaxes[i];
  535. if (axis && axis.used) {
  536. key = "y" + axis.n;
  537. if (pos[key] == null && axis.n === 1) {
  538. key = "y";
  539. }
  540. if (pos[key] != null) {
  541. res.top = axis.p2c(pos[key]);
  542. break;
  543. }
  544. }
  545. }
  546. return res;
  547. }
  548. function getOrCreateAxis(axes, number) {
  549. if (!axes[number - 1]) {
  550. axes[number - 1] = {
  551. n: number, // save the number for future reference
  552. direction: axes === xaxes ? "x" : "y",
  553. options: $.extend(true, {}, axes === xaxes ? options.xaxis : options.yaxis)
  554. };
  555. }
  556. return axes[number - 1];
  557. }
  558. function fillInSeriesOptions() {
  559. var neededColors = series.length,
  560. maxIndex = -1,
  561. i;
  562. // Subtract the number of series that already have fixed colors or
  563. // color indexes from the number that we still need to generate.
  564. for (i = 0; i < series.length; ++i) {
  565. var sc = series[i].color;
  566. if (sc != null) {
  567. neededColors--;
  568. if (typeof sc === "number" && sc > maxIndex) {
  569. maxIndex = sc;
  570. }
  571. }
  572. }
  573. // If any of the series have fixed color indexes, then we need to
  574. // generate at least as many colors as the highest index.
  575. if (neededColors <= maxIndex) {
  576. neededColors = maxIndex + 1;
  577. }
  578. // Generate all the colors, using first the option colors and then
  579. // variations on those colors once they're exhausted.
  580. var c, colors = [],
  581. colorPool = options.colors,
  582. colorPoolSize = colorPool.length,
  583. variation = 0,
  584. definedColors = Math.max(0, series.length - neededColors);
  585. for (i = 0; i < neededColors; i++) {
  586. c = $.color.parse(colorPool[(definedColors + i) % colorPoolSize] || "#666");
  587. // Each time we exhaust the colors in the pool we adjust
  588. // a scaling factor used to produce more variations on
  589. // those colors. The factor alternates negative/positive
  590. // to produce lighter/darker colors.
  591. // Reset the variation after every few cycles, or else
  592. // it will end up producing only white or black colors.
  593. if (i % colorPoolSize === 0 && i) {
  594. if (variation >= 0) {
  595. if (variation < 0.5) {
  596. variation = -variation - 0.2;
  597. } else variation = 0;
  598. } else variation = -variation;
  599. }
  600. colors[i] = c.scale('rgb', 1 + variation);
  601. }
  602. // Finalize the series options, filling in their colors
  603. var colori = 0,
  604. s;
  605. for (i = 0; i < series.length; ++i) {
  606. s = series[i];
  607. // assign colors
  608. if (s.color == null) {
  609. s.color = colors[colori].toString();
  610. ++colori;
  611. } else if (typeof s.color === "number") {
  612. s.color = colors[s.color].toString();
  613. }
  614. // turn on lines automatically in case nothing is set
  615. if (s.lines.show == null) {
  616. var v, show = true;
  617. for (v in s) {
  618. if (s[v] && s[v].show) {
  619. show = false;
  620. break;
  621. }
  622. }
  623. if (show) {
  624. s.lines.show = true;
  625. }
  626. }
  627. // If nothing was provided for lines.zero, default it to match
  628. // lines.fill, since areas by default should extend to zero.
  629. if (s.lines.zero == null) {
  630. s.lines.zero = !!s.lines.fill;
  631. }
  632. // setup axes
  633. s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
  634. s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
  635. }
  636. }
  637. function processData(prevSeries) {
  638. var topSentry = Number.POSITIVE_INFINITY,
  639. bottomSentry = Number.NEGATIVE_INFINITY,
  640. i, j, k, m,
  641. s, points, ps, val, f, p,
  642. data, format;
  643. function updateAxis(axis, min, max) {
  644. if (min < axis.datamin && min !== -Infinity) {
  645. axis.datamin = min;
  646. }
  647. if (max > axis.datamax && max !== Infinity) {
  648. axis.datamax = max;
  649. }
  650. }
  651. function reusePoints(prevSeries, i) {
  652. if (prevSeries && prevSeries[i] && prevSeries[i].datapoints && prevSeries[i].datapoints.points) {
  653. return prevSeries[i].datapoints.points;
  654. }
  655. return [];
  656. }
  657. $.each(allAxes(), function(_, axis) {
  658. // init axis
  659. if (axis.options.growOnly !== true) {
  660. axis.datamin = topSentry;
  661. axis.datamax = bottomSentry;
  662. } else {
  663. if (axis.datamin === undefined) {
  664. axis.datamin = topSentry;
  665. }
  666. if (axis.datamax === undefined) {
  667. axis.datamax = bottomSentry;
  668. }
  669. }
  670. axis.used = false;
  671. });
  672. for (i = 0; i < series.length; ++i) {
  673. s = series[i];
  674. s.datapoints = {
  675. points: []
  676. };
  677. if (s.datapoints.points.length === 0) {
  678. s.datapoints.points = reusePoints(prevSeries, i);
  679. }
  680. executeHooks(hooks.processRawData, [s, s.data, s.datapoints]);
  681. }
  682. // first pass: clean and copy data
  683. for (i = 0; i < series.length; ++i) {
  684. s = series[i];
  685. data = s.data;
  686. format = s.datapoints.format;
  687. if (!format) {
  688. format = [];
  689. // find out how to copy
  690. format.push({
  691. x: true,
  692. y: false,
  693. number: true,
  694. required: true,
  695. computeRange: s.xaxis.options.autoScale !== 'none',
  696. defaultValue: null
  697. });
  698. format.push({
  699. x: false,
  700. y: true,
  701. number: true,
  702. required: true,
  703. computeRange: s.yaxis.options.autoScale !== 'none',
  704. defaultValue: null
  705. });
  706. if (s.stack || s.bars.show || (s.lines.show && s.lines.fill)) {
  707. var expectedPs = s.datapoints.pointsize != null ? s.datapoints.pointsize : (s.data && s.data[0] && s.data[0].length ? s.data[0].length : 3);
  708. if (expectedPs > 2) {
  709. format.push({
  710. x: false,
  711. y: true,
  712. number: true,
  713. required: false,
  714. computeRange: s.yaxis.options.autoScale !== 'none',
  715. defaultValue: 0
  716. });
  717. }
  718. }
  719. s.datapoints.format = format;
  720. }
  721. s.xaxis.used = s.yaxis.used = true;
  722. if (s.datapoints.pointsize != null) continue; // already filled in
  723. s.datapoints.pointsize = format.length;
  724. ps = s.datapoints.pointsize;
  725. points = s.datapoints.points;
  726. var insertSteps = s.lines.show && s.lines.steps;
  727. for (j = k = 0; j < data.length; ++j, k += ps) {
  728. p = data[j];
  729. var nullify = p == null;
  730. if (!nullify) {
  731. for (m = 0; m < ps; ++m) {
  732. val = p[m];
  733. f = format[m];
  734. if (f) {
  735. if (f.number && val != null) {
  736. val = +val; // convert to number
  737. if (isNaN(val)) {
  738. val = null;
  739. }
  740. }
  741. if (val == null) {
  742. if (f.required) nullify = true;
  743. if (f.defaultValue != null) val = f.defaultValue;
  744. }
  745. }
  746. points[k + m] = val;
  747. }
  748. }
  749. if (nullify) {
  750. for (m = 0; m < ps; ++m) {
  751. val = points[k + m];
  752. if (val != null) {
  753. f = format[m];
  754. // extract min/max info
  755. if (f.computeRange) {
  756. if (f.x) {
  757. updateAxis(s.xaxis, val, val);
  758. }
  759. if (f.y) {
  760. updateAxis(s.yaxis, val, val);
  761. }
  762. }
  763. }
  764. points[k + m] = null;
  765. }
  766. }
  767. }
  768. points.length = k; //trims the internal buffer to the correct length
  769. }
  770. // give the hooks a chance to run
  771. for (i = 0; i < series.length; ++i) {
  772. s = series[i];
  773. executeHooks(hooks.processDatapoints, [s, s.datapoints]);
  774. }
  775. // second pass: find datamax/datamin for auto-scaling
  776. for (i = 0; i < series.length; ++i) {
  777. s = series[i];
  778. format = s.datapoints.format;
  779. if (format.every(function (f) { return !f.computeRange; })) {
  780. continue;
  781. }
  782. var range = plot.adjustSeriesDataRange(s,
  783. plot.computeRangeForDataSeries(s));
  784. executeHooks(hooks.adjustSeriesDataRange, [s, range]);
  785. updateAxis(s.xaxis, range.xmin, range.xmax);
  786. updateAxis(s.yaxis, range.ymin, range.ymax);
  787. }
  788. $.each(allAxes(), function(_, axis) {
  789. if (axis.datamin === topSentry) {
  790. axis.datamin = null;
  791. }
  792. if (axis.datamax === bottomSentry) {
  793. axis.datamax = null;
  794. }
  795. });
  796. }
  797. function setupCanvases() {
  798. // Make sure the placeholder is clear of everything except canvases
  799. // from a previous plot in this container that we'll try to re-use.
  800. placeholder.css("padding", 0) // padding messes up the positioning
  801. .children().filter(function() {
  802. return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base');
  803. }).remove();
  804. if (placeholder.css("position") === 'static') {
  805. placeholder.css("position", "relative"); // for positioning labels and overlay
  806. }
  807. surface = new Canvas("flot-base", placeholder[0]);
  808. overlay = new Canvas("flot-overlay", placeholder[0]); // overlay canvas for interactive features
  809. ctx = surface.context;
  810. octx = overlay.context;
  811. // define which element we're listening for events on
  812. eventHolder = $(overlay.element).unbind();
  813. // If we're re-using a plot object, shut down the old one
  814. var existing = placeholder.data("plot");
  815. if (existing) {
  816. existing.shutdown();
  817. overlay.clear();
  818. }
  819. // save in case we get replotted
  820. placeholder.data("plot", plot);
  821. }
  822. function bindEvents() {
  823. executeHooks(hooks.bindEvents, [eventHolder]);
  824. }
  825. function addEventHandler(event, handler, eventHolder, priority) {
  826. var key = eventHolder + event;
  827. var eventList = eventManager[key] || [];
  828. eventList.push({"event": event, "handler": handler, "eventHolder": eventHolder, "priority": priority});
  829. eventList.sort((a, b) => b.priority - a.priority );
  830. eventList.forEach( eventData => {
  831. eventData.eventHolder.unbind(eventData.event, eventData.handler);
  832. eventData.eventHolder.bind(eventData.event, eventData.handler);
  833. });
  834. eventManager[key] = eventList;
  835. }
  836. function shutdown() {
  837. if (redrawTimeout) {
  838. clearTimeout(redrawTimeout);
  839. }
  840. executeHooks(hooks.shutdown, [eventHolder]);
  841. }
  842. function setTransformationHelpers(axis) {
  843. // set helper functions on the axis, assumes plot area
  844. // has been computed already
  845. function identity(x) {
  846. return x;
  847. }
  848. var s, m, t = axis.options.transform || identity,
  849. it = axis.options.inverseTransform;
  850. // precompute how much the axis is scaling a point
  851. // in canvas space
  852. if (axis.direction === "x") {
  853. if (isFinite(t(axis.max) - t(axis.min))) {
  854. s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
  855. } else {
  856. s = axis.scale = 1 / Math.abs($.plot.saturated.delta(t(axis.min), t(axis.max), plotWidth));
  857. }
  858. m = Math.min(t(axis.max), t(axis.min));
  859. } else {
  860. if (isFinite(t(axis.max) - t(axis.min))) {
  861. s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
  862. } else {
  863. s = axis.scale = 1 / Math.abs($.plot.saturated.delta(t(axis.min), t(axis.max), plotHeight));
  864. }
  865. s = -s;
  866. m = Math.max(t(axis.max), t(axis.min));
  867. }
  868. // data point to canvas coordinate
  869. if (t === identity) {
  870. // slight optimization
  871. axis.p2c = function(p) {
  872. if (isFinite(p - m)) {
  873. return (p - m) * s;
  874. } else {
  875. return (p / 4 - m / 4) * s * 4;
  876. }
  877. };
  878. } else {
  879. axis.p2c = function(p) {
  880. var tp = t(p);
  881. if (isFinite(tp - m)) {
  882. return (tp - m) * s;
  883. } else {
  884. return (tp / 4 - m / 4) * s * 4;
  885. }
  886. };
  887. }
  888. // canvas coordinate to data point
  889. if (!it) {
  890. axis.c2p = function(c) {
  891. return m + c / s;
  892. };
  893. } else {
  894. axis.c2p = function(c) {
  895. return it(m + c / s);
  896. };
  897. }
  898. }
  899. function measureTickLabels(axis) {
  900. var opts = axis.options,
  901. ticks = opts.showTickLabels !== 'none' && axis.ticks ? axis.ticks : [],
  902. showMajorTickLabels = opts.showTickLabels === 'major' || opts.showTickLabels === 'all',
  903. showEndpointsTickLabels = opts.showTickLabels === 'endpoints' || opts.showTickLabels === 'all',
  904. labelWidth = opts.labelWidth || 0,
  905. labelHeight = opts.labelHeight || 0,
  906. legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
  907. layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
  908. font = opts.font || "flot-tick-label tickLabel";
  909. for (var i = 0; i < ticks.length; ++i) {
  910. var t = ticks[i];
  911. var label = t.label;
  912. if (!t.label ||
  913. (showMajorTickLabels === false && i > 0 && i < ticks.length - 1) ||
  914. (showEndpointsTickLabels === false && (i === 0 || i === ticks.length - 1))) {
  915. continue;
  916. }
  917. if (typeof t.label === 'object') {
  918. label = t.label.name;
  919. }
  920. var info = surface.getTextInfo(layer, label, font);
  921. labelWidth = Math.max(labelWidth, info.width);
  922. labelHeight = Math.max(labelHeight, info.height);
  923. }
  924. axis.labelWidth = opts.labelWidth || labelWidth;
  925. axis.labelHeight = opts.labelHeight || labelHeight;
  926. }
  927. function allocateAxisBoxFirstPhase(axis) {
  928. // find the bounding box of the axis by looking at label
  929. // widths/heights and ticks, make room by diminishing the
  930. // plotOffset; this first phase only looks at one
  931. // dimension per axis, the other dimension depends on the
  932. // other axes so will have to wait
  933. // here reserve additional space
  934. executeHooks(hooks.axisReserveSpace, [axis]);
  935. var lw = axis.labelWidth,
  936. lh = axis.labelHeight,
  937. pos = axis.options.position,
  938. isXAxis = axis.direction === "x",
  939. tickLength = axis.options.tickLength,
  940. showTicks = axis.options.showTicks,
  941. showMinorTicks = axis.options.showMinorTicks,
  942. gridLines = axis.options.gridLines,
  943. axisMargin = options.grid.axisMargin,
  944. padding = options.grid.labelMargin,
  945. innermost = true,
  946. outermost = true,
  947. found = false;
  948. // Determine the axis's position in its direction and on its side
  949. $.each(isXAxis ? xaxes : yaxes, function(i, a) {
  950. if (a && (a.show || a.reserveSpace)) {
  951. if (a === axis) {
  952. found = true;
  953. } else if (a.options.position === pos) {
  954. if (found) {
  955. outermost = false;
  956. } else {
  957. innermost = false;
  958. }
  959. }
  960. }
  961. });
  962. // The outermost axis on each side has no margin
  963. if (outermost) {
  964. axisMargin = 0;
  965. }
  966. // Set the default tickLength if necessary
  967. if (tickLength == null) {
  968. tickLength = TICK_LENGTH_CONSTANT;
  969. }
  970. // By default, major tick marks are visible
  971. if (showTicks == null) {
  972. showTicks = true;
  973. }
  974. // By default, minor tick marks are visible
  975. if (showMinorTicks == null) {
  976. showMinorTicks = true;
  977. }
  978. // By default, grid lines are visible
  979. if (gridLines == null) {
  980. if (innermost) {
  981. gridLines = true;
  982. } else {
  983. gridLines = false;
  984. }
  985. }
  986. if (!isNaN(+tickLength)) {
  987. padding += showTicks ? +tickLength : 0;
  988. }
  989. if (isXAxis) {
  990. lh += padding;
  991. if (pos === "bottom") {
  992. plotOffset.bottom += lh + axisMargin;
  993. axis.box = {
  994. top: surface.height - plotOffset.bottom,
  995. height: lh
  996. };
  997. } else {
  998. axis.box = {
  999. top: plotOffset.top + axisMargin,
  1000. height: lh
  1001. };
  1002. plotOffset.top += lh + axisMargin;
  1003. }
  1004. } else {
  1005. lw += padding;
  1006. if (pos === "left") {
  1007. axis.box = {
  1008. left: plotOffset.left + axisMargin,
  1009. width: lw
  1010. };
  1011. plotOffset.left += lw + axisMargin;
  1012. } else {
  1013. plotOffset.right += lw + axisMargin;
  1014. axis.box = {
  1015. left: surface.width - plotOffset.right,
  1016. width: lw
  1017. };
  1018. }
  1019. }
  1020. // save for future reference
  1021. axis.position = pos;
  1022. axis.tickLength = tickLength;
  1023. axis.showMinorTicks = showMinorTicks;
  1024. axis.showTicks = showTicks;
  1025. axis.gridLines = gridLines;
  1026. axis.box.padding = padding;
  1027. axis.innermost = innermost;
  1028. }
  1029. function allocateAxisBoxSecondPhase(axis) {
  1030. // now that all axis boxes have been placed in one
  1031. // dimension, we can set the remaining dimension coordinates
  1032. if (axis.direction === "x") {
  1033. axis.box.left = plotOffset.left - axis.labelWidth / 2;
  1034. axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
  1035. } else {
  1036. axis.box.top = plotOffset.top - axis.labelHeight / 2;
  1037. axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
  1038. }
  1039. }
  1040. function adjustLayoutForThingsStickingOut() {
  1041. // possibly adjust plot offset to ensure everything stays
  1042. // inside the canvas and isn't clipped off
  1043. var minMargin = options.grid.minBorderMargin,
  1044. i;
  1045. // check stuff from the plot (FIXME: this should just read
  1046. // a value from the series, otherwise it's impossible to
  1047. // customize)
  1048. if (minMargin == null) {
  1049. minMargin = 0;
  1050. for (i = 0; i < series.length; ++i) {
  1051. minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth / 2));
  1052. }
  1053. }
  1054. var a, offset = {},
  1055. margins = {
  1056. left: minMargin,
  1057. right: minMargin,
  1058. top: minMargin,
  1059. bottom: minMargin
  1060. };
  1061. // check axis labels, note we don't check the actual
  1062. // labels but instead use the overall width/height to not
  1063. // jump as much around with replots
  1064. $.each(allAxes(), function(_, axis) {
  1065. if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
  1066. if (axis.direction === "x") {
  1067. margins.left = Math.max(margins.left, axis.labelWidth / 2);
  1068. margins.right = Math.max(margins.right, axis.labelWidth / 2);
  1069. } else {
  1070. margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
  1071. margins.top = Math.max(margins.top, axis.labelHeight / 2);
  1072. }
  1073. }
  1074. });
  1075. for (a in margins) {
  1076. offset[a] = margins[a] - plotOffset[a];
  1077. }
  1078. $.each(xaxes.concat(yaxes), function(_, axis) {
  1079. alignAxisWithGrid(axis, offset, function (offset) {
  1080. return offset > 0;
  1081. });
  1082. });
  1083. plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
  1084. plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
  1085. plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
  1086. plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
  1087. }
  1088. function alignAxisWithGrid(axis, offset, isValid) {
  1089. if (axis.direction === "x") {
  1090. if (axis.position === "bottom" && isValid(offset.bottom)) {
  1091. axis.box.top -= Math.ceil(offset.bottom);
  1092. }
  1093. if (axis.position === "top" && isValid(offset.top)) {
  1094. axis.box.top += Math.ceil(offset.top);
  1095. }
  1096. } else {
  1097. if (axis.position === "left" && isValid(offset.left)) {
  1098. axis.box.left += Math.ceil(offset.left);
  1099. }
  1100. if (axis.position === "right" && isValid(offset.right)) {
  1101. axis.box.left -= Math.ceil(offset.right);
  1102. }
  1103. }
  1104. }
  1105. function setupGrid(autoScale) {
  1106. var i, a, axes = allAxes(),
  1107. showGrid = options.grid.show;
  1108. // Initialize the plot's offset from the edge of the canvas
  1109. for (a in plotOffset) {
  1110. plotOffset[a] = 0;
  1111. }
  1112. executeHooks(hooks.processOffset, [plotOffset]);
  1113. // If the grid is visible, add its border width to the offset
  1114. for (a in plotOffset) {
  1115. if (typeof (options.grid.borderWidth) === "object") {
  1116. plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
  1117. } else {
  1118. plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
  1119. }
  1120. }
  1121. $.each(axes, function(_, axis) {
  1122. var axisOpts = axis.options;
  1123. axis.show = axisOpts.show == null ? axis.used : axisOpts.show;
  1124. axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace;
  1125. setupTickFormatter(axis);
  1126. executeHooks(hooks.setRange, [axis, autoScale]);
  1127. setRange(axis, autoScale);
  1128. });
  1129. if (showGrid) {
  1130. plotWidth = surface.width - plotOffset.left - plotOffset.right;
  1131. plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
  1132. var allocatedAxes = $.grep(axes, function(axis) {
  1133. return axis.show || axis.reserveSpace;
  1134. });
  1135. $.each(allocatedAxes, function(_, axis) {
  1136. // make the ticks
  1137. setupTickGeneration(axis);
  1138. setMajorTicks(axis);
  1139. snapRangeToTicks(axis, axis.ticks);
  1140. //for computing the endpoints precision, transformationHelpers are needed
  1141. setTransformationHelpers(axis);
  1142. setEndpointTicks(axis, series);
  1143. // find labelWidth/Height for axis
  1144. measureTickLabels(axis);
  1145. });
  1146. // with all dimensions calculated, we can compute the
  1147. // axis bounding boxes, start from the outside
  1148. // (reverse order)
  1149. for (i = allocatedAxes.length - 1; i >= 0; --i) {
  1150. allocateAxisBoxFirstPhase(allocatedAxes[i]);
  1151. }
  1152. // make sure we've got enough space for things that
  1153. // might stick out
  1154. adjustLayoutForThingsStickingOut();
  1155. $.each(allocatedAxes, function(_, axis) {
  1156. allocateAxisBoxSecondPhase(axis);
  1157. });
  1158. }
  1159. //adjust axis and plotOffset according to grid.margins
  1160. if (options.grid.margin) {
  1161. for (a in plotOffset) {
  1162. var margin = options.grid.margin || 0;
  1163. plotOffset[a] += typeof margin === "number" ? margin : (margin[a] || 0);
  1164. }
  1165. $.each(xaxes.concat(yaxes), function(_, axis) {
  1166. alignAxisWithGrid(axis, options.grid.margin, function(offset) {
  1167. return offset !== undefined && offset !== null;
  1168. });
  1169. });
  1170. }
  1171. //after adjusting the axis, plot width and height will be modified
  1172. plotWidth = surface.width - plotOffset.left - plotOffset.right;
  1173. plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
  1174. // now we got the proper plot dimensions, we can compute the scaling
  1175. $.each(axes, function(_, axis) {
  1176. setTransformationHelpers(axis);
  1177. });
  1178. if (showGrid) {
  1179. drawAxisLabels();
  1180. }
  1181. executeHooks(hooks.setupGrid, []);
  1182. }
  1183. function widenMinMax(minimum, maximum) {
  1184. var min = (minimum === undefined ? null : minimum);
  1185. var max = (maximum === undefined ? null : maximum);
  1186. var delta = max - min;
  1187. if (delta === 0.0) {
  1188. // degenerate case
  1189. var widen = max === 0 ? 1 : 0.01;
  1190. var wmin = null;
  1191. if (min == null) {
  1192. wmin -= widen;
  1193. }
  1194. // always widen max if we couldn't widen min to ensure we
  1195. // don't fall into min == max which doesn't work
  1196. if (max == null || min != null) {
  1197. max += widen;
  1198. }
  1199. if (wmin != null) {
  1200. min = wmin;
  1201. }
  1202. }
  1203. return {
  1204. min: min,
  1205. max: max
  1206. };
  1207. }
  1208. function autoScaleAxis(axis) {
  1209. var opts = axis.options,
  1210. min = opts.min,
  1211. max = opts.max,
  1212. datamin = axis.datamin,
  1213. datamax = axis.datamax,
  1214. delta;
  1215. switch (opts.autoScale) {
  1216. case "none":
  1217. min = +(opts.min != null ? opts.min : datamin);
  1218. max = +(opts.max != null ? opts.max : datamax);
  1219. break;
  1220. case "loose":
  1221. if (datamin != null && datamax != null) {
  1222. min = datamin;
  1223. max = datamax;
  1224. delta = $.plot.saturated.saturate(max - min);
  1225. var margin = ((typeof opts.autoScaleMargin === 'number') ? opts.autoScaleMargin : 0.02);
  1226. min = $.plot.saturated.saturate(min - delta * margin);
  1227. max = $.plot.saturated.saturate(max + delta * margin);
  1228. // make sure we don't go below zero if all values are positive
  1229. if (min < 0 && datamin >= 0) {
  1230. min = 0;
  1231. }
  1232. } else {
  1233. min = opts.min;
  1234. max = opts.max;
  1235. }
  1236. break;
  1237. case "exact":
  1238. min = (datamin != null ? datamin : opts.min);
  1239. max = (datamax != null ? datamax : opts.max);
  1240. break;
  1241. case "sliding-window":
  1242. if (datamax > max) {
  1243. // move the window to fit the new data,
  1244. // keeping the axis range constant
  1245. max = datamax;
  1246. min = Math.max(datamax - (opts.windowSize || 100), min);
  1247. }
  1248. break;
  1249. }
  1250. var widenedMinMax = widenMinMax(min, max);
  1251. min = widenedMinMax.min;
  1252. max = widenedMinMax.max;
  1253. // grow loose or grow exact supported
  1254. if (opts.growOnly === true && opts.autoScale !== "none" && opts.autoScale !== "sliding-window") {
  1255. min = (min < datamin) ? min : (datamin !== null ? datamin : min);
  1256. max = (max > datamax) ? max : (datamax !== null ? datamax : max);
  1257. }
  1258. axis.autoScaledMin = min;
  1259. axis.autoScaledMax = max;
  1260. }
  1261. function setRange(axis, autoScale) {
  1262. var min = typeof axis.options.min === 'number' ? axis.options.min : axis.min,
  1263. max = typeof axis.options.max === 'number' ? axis.options.max : axis.max,
  1264. plotOffset = axis.options.offset;
  1265. if (autoScale) {
  1266. autoScaleAxis(axis);
  1267. min = axis.autoScaledMin;
  1268. max = axis.autoScaledMax;
  1269. }
  1270. min = (min != null ? min : -1) + (plotOffset.below || 0);
  1271. max = (max != null ? max : 1) + (plotOffset.above || 0);
  1272. if (min > max) {
  1273. var tmp = min;
  1274. min = max;
  1275. max = tmp;
  1276. axis.options.offset = { above: 0, below: 0 };
  1277. }
  1278. axis.min = $.plot.saturated.saturate(min);
  1279. axis.max = $.plot.saturated.saturate(max);
  1280. }
  1281. function computeValuePrecision (min, max, direction, ticks, tickDecimals) {
  1282. var noTicks = fixupNumberOfTicks(direction, surface, ticks);
  1283. var delta = $.plot.saturated.delta(min, max, noTicks),
  1284. dec = -Math.floor(Math.log(delta) / Math.LN10);
  1285. //if it is called with tickDecimals, then the precision should not be greather then that
  1286. if (tickDecimals && dec > tickDecimals) {
  1287. dec = tickDecimals;
  1288. }
  1289. var magn = Math.pow(10, -dec),
  1290. norm = delta / magn;
  1291. if (norm > 2.25 && norm < 3 && (dec + 1) <= tickDecimals) {
  1292. //we need an extra decimals when tickSize is 2.5
  1293. ++dec;
  1294. }
  1295. return isFinite(dec) ? dec : 0;
  1296. };
  1297. function computeTickSize (min, max, noTicks, tickDecimals) {
  1298. var delta = $.plot.saturated.delta(min, max, noTicks),
  1299. dec = -Math.floor(Math.log(delta) / Math.LN10);
  1300. //if it is called with tickDecimals, then the precision should not be greather then that
  1301. if (tickDecimals && dec > tickDecimals) {
  1302. dec = tickDecimals;
  1303. }
  1304. var magn = Math.pow(10, -dec),
  1305. norm = delta / magn, // norm is between 1.0 and 10.0
  1306. size;
  1307. if (norm < 1.5) {
  1308. size = 1;
  1309. } else if (norm < 3) {
  1310. size = 2;
  1311. if (norm > 2.25 && (tickDecimals == null || (dec + 1) <= tickDecimals)) {
  1312. size = 2.5;
  1313. }
  1314. } else if (norm < 7.5) {
  1315. size = 5;
  1316. } else {
  1317. size = 10;
  1318. }
  1319. size *= magn;
  1320. return size;
  1321. }
  1322. function getAxisTickSize(min, max, direction, options, tickDecimals) {
  1323. var noTicks;
  1324. if (typeof options.ticks === "number" && options.ticks > 0) {
  1325. noTicks = options.ticks;
  1326. } else {
  1327. // heuristic based on the model a*sqrt(x) fitted to
  1328. // some data points that seemed reasonable
  1329. noTicks = 0.3 * Math.sqrt(direction === "x" ? surface.width : surface.height);
  1330. }
  1331. var size = computeTickSize(min, max, noTicks, tickDecimals);
  1332. if (options.minTickSize != null && size < options.minTickSize) {
  1333. size = options.minTickSize;
  1334. }
  1335. return options.tickSize || size;
  1336. };
  1337. function fixupNumberOfTicks(direction, surface, ticksOption) {
  1338. var noTicks;
  1339. if (typeof ticksOption === "number" && ticksOption > 0) {
  1340. noTicks = ticksOption;
  1341. } else {
  1342. noTicks = 0.3 * Math.sqrt(direction === "x" ? surface.width : surface.height);
  1343. }
  1344. return noTicks;
  1345. }
  1346. function setupTickFormatter(axis) {
  1347. var opts = axis.options;
  1348. if (!axis.tickFormatter) {
  1349. if (typeof opts.tickFormatter === 'function') {
  1350. axis.tickFormatter = function() {
  1351. var args = Array.prototype.slice.call(arguments);
  1352. return "" + opts.tickFormatter.apply(null, args);
  1353. };
  1354. } else {
  1355. axis.tickFormatter = defaultTickFormatter;
  1356. }
  1357. }
  1358. }
  1359. function setupTickGeneration(axis) {
  1360. var opts = axis.options;
  1361. var noTicks;
  1362. noTicks = fixupNumberOfTicks(axis.direction, surface, opts.ticks);
  1363. axis.delta = $.plot.saturated.delta(axis.min, axis.max, noTicks);
  1364. var precision = plot.computeValuePrecision(axis.min, axis.max, axis.direction, noTicks, opts.tickDecimals);
  1365. axis.tickDecimals = Math.max(0, opts.tickDecimals != null ? opts.tickDecimals : precision);
  1366. axis.tickSize = getAxisTickSize(axis.min, axis.max, axis.direction, opts, opts.tickDecimals);
  1367. // Flot supports base-10 axes; any other mode else is handled by a plug-in,
  1368. // like flot.time.js.
  1369. if (!axis.tickGenerator) {
  1370. if (typeof opts.tickGenerator === 'function') {
  1371. axis.tickGenerator = opts.tickGenerator;
  1372. } else {
  1373. axis.tickGenerator = defaultTickGenerator;
  1374. }
  1375. }
  1376. if (opts.alignTicksWithAxis != null) {
  1377. var otherAxis = (axis.direction === "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
  1378. if (otherAxis && otherAxis.used && otherAxis !== axis) {
  1379. // consider snapping min/max to outermost nice ticks
  1380. var niceTicks = axis.tickGenerator(axis, plot);
  1381. if (niceTicks.length > 0) {
  1382. if (opts.min == null) {
  1383. axis.min = Math.min(axis.min, niceTicks[0]);
  1384. }
  1385. if (opts.max == null && niceTicks.length > 1) {
  1386. axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
  1387. }
  1388. }
  1389. axis.tickGenerator = function(axis) {
  1390. // copy ticks, scaled to this axis
  1391. var ticks = [],
  1392. v, i;
  1393. for (i = 0; i < otherAxis.ticks.length; ++i) {
  1394. v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
  1395. v = axis.min + v * (axis.max - axis.min);
  1396. ticks.push(v);
  1397. }
  1398. return ticks;
  1399. };
  1400. // we might need an extra decimal since forced
  1401. // ticks don't necessarily fit naturally
  1402. if (!axis.mode && opts.tickDecimals == null) {
  1403. var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
  1404. ts = axis.tickGenerator(axis, plot);
  1405. // only proceed if the tick interval rounded
  1406. // with an extra decimal doesn't give us a
  1407. // zero at end
  1408. if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) {
  1409. axis.tickDecimals = extraDec;
  1410. }
  1411. }
  1412. }
  1413. }
  1414. }
  1415. function setMajorTicks(axis) {
  1416. var oticks = axis.options.ticks,
  1417. ticks = [];
  1418. if (oticks == null || (typeof oticks === "number" && oticks > 0)) {
  1419. ticks = axis.tickGenerator(axis, plot);
  1420. } else if (oticks) {
  1421. if ($.isFunction(oticks)) {
  1422. // generate the ticks
  1423. ticks = oticks(axis);
  1424. } else {
  1425. ticks = oticks;
  1426. }
  1427. }
  1428. // clean up/labelify the supplied ticks, copy them over
  1429. var i, v;
  1430. axis.ticks = [];
  1431. for (i = 0; i < ticks.length; ++i) {
  1432. var label = null;
  1433. var t = ticks[i];
  1434. if (typeof t === "object") {
  1435. v = +t[0];
  1436. if (t.length > 1) {
  1437. label = t[1];
  1438. }
  1439. } else {
  1440. v = +t;
  1441. }
  1442. if (!isNaN(v)) {
  1443. axis.ticks.push(
  1444. newTick(v, label, axis, 'major'));
  1445. }
  1446. }
  1447. }
  1448. function newTick(v, label, axis, type) {
  1449. if (label === null) {
  1450. switch (type) {
  1451. case 'min':
  1452. case 'max':
  1453. //improving the precision of endpoints
  1454. var precision = getEndpointPrecision(v, axis);
  1455. label = isFinite(precision) ? axis.tickFormatter(v, axis, precision, plot) : axis.tickFormatter(v, axis, precision, plot);
  1456. break;
  1457. case 'major':
  1458. label = axis.tickFormatter(v, axis, undefined, plot);
  1459. }
  1460. }
  1461. return {
  1462. v: v,
  1463. label: label
  1464. };
  1465. }
  1466. function snapRangeToTicks(axis, ticks) {
  1467. if (axis.options.autoScale === "loose" && ticks.length > 0) {
  1468. // snap to ticks
  1469. axis.min = Math.min(axis.min, ticks[0].v);
  1470. axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
  1471. }
  1472. }
  1473. function getEndpointPrecision(value, axis) {
  1474. var canvas1 = Math.floor(axis.p2c(value)),
  1475. canvas2 = axis.direction === "x" ? canvas1 + 1 : canvas1 - 1,
  1476. point1 = axis.c2p(canvas1),
  1477. point2 = axis.c2p(canvas2),
  1478. precision = computeValuePrecision(point1, point2, axis.direction, 1);
  1479. return precision;
  1480. }
  1481. function setEndpointTicks(axis, series) {
  1482. if (isValidEndpointTick(axis, series)) {
  1483. axis.ticks.unshift(newTick(axis.min, null, axis, 'min'));
  1484. axis.ticks.push(newTick(axis.max, null, axis, 'max'));
  1485. }
  1486. }
  1487. function isValidEndpointTick(axis, series) {
  1488. if (axis.options.showTickLabels === 'endpoints') {
  1489. return true;
  1490. }
  1491. if (axis.options.showTickLabels === 'all') {
  1492. var associatedSeries = series.filter(function(s) {
  1493. return s.xaxis === axis;
  1494. }),
  1495. notAllBarSeries = associatedSeries.some(function(s) {
  1496. return !s.bars.show;
  1497. });
  1498. return associatedSeries.length === 0 || notAllBarSeries;
  1499. }
  1500. if (axis.options.showTickLabels === 'major' || axis.options.showTickLabels === 'none') {
  1501. return false;
  1502. }
  1503. }
  1504. function draw() {
  1505. surface.clear();
  1506. executeHooks(hooks.drawBackground, [ctx]);
  1507. var grid = options.grid;
  1508. // draw background, if any
  1509. if (grid.show && grid.backgroundColor) {
  1510. drawBackground();
  1511. }
  1512. if (grid.show && !grid.aboveData) {
  1513. drawGrid();
  1514. }
  1515. for (var i = 0; i < series.length; ++i) {
  1516. executeHooks(hooks.drawSeries, [ctx, series[i], i, getColorOrGradient]);
  1517. drawSeries(series[i]);
  1518. }
  1519. executeHooks(hooks.draw, [ctx]);
  1520. if (grid.show && grid.aboveData) {
  1521. drawGrid();
  1522. }
  1523. surface.render();
  1524. // A draw implies that either the axes or data have changed, so we
  1525. // should probably update the overlay highlights as well.
  1526. triggerRedrawOverlay();
  1527. }
  1528. function extractRange(ranges, coord) {
  1529. var axis, from, to, key, axes = allAxes();
  1530. for (var i = 0; i < axes.length; ++i) {
  1531. axis = axes[i];
  1532. if (axis.direction === coord) {
  1533. key = coord + axis.n + "axis";
  1534. if (!ranges[key] && axis.n === 1) {
  1535. // support x1axis as xaxis
  1536. key = coord + "axis";
  1537. }
  1538. if (ranges[key]) {
  1539. from = ranges[key].from;
  1540. to = ranges[key].to;
  1541. break;
  1542. }
  1543. }
  1544. }
  1545. // backwards-compat stuff - to be removed in future
  1546. if (!ranges[key]) {
  1547. axis = coord === "x" ? xaxes[0] : yaxes[0];
  1548. from = ranges[coord + "1"];
  1549. to = ranges[coord + "2"];
  1550. }
  1551. // auto-reverse as an added bonus
  1552. if (from != null && to != null && from > to) {
  1553. var tmp = from;
  1554. from = to;
  1555. to = tmp;
  1556. }
  1557. return {
  1558. from: from,
  1559. to: to,
  1560. axis: axis
  1561. };
  1562. }
  1563. function drawBackground() {
  1564. ctx.save();
  1565. ctx.translate(plotOffset.left, plotOffset.top);
  1566. ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
  1567. ctx.fillRect(0, 0, plotWidth, plotHeight);
  1568. ctx.restore();
  1569. }
  1570. function drawMarkings() {
  1571. // draw markings
  1572. var markings = options.grid.markings,
  1573. axes;
  1574. if (markings) {
  1575. if ($.isFunction(markings)) {
  1576. axes = plot.getAxes();
  1577. // xmin etc. is backwards compatibility, to be
  1578. // removed in the future
  1579. axes.xmin = axes.xaxis.min;
  1580. axes.xmax = axes.xaxis.max;
  1581. axes.ymin = axes.yaxis.min;
  1582. axes.ymax = axes.yaxis.max;
  1583. markings = markings(axes);
  1584. }
  1585. var i;
  1586. for (i = 0; i < markings.length; ++i) {
  1587. var m = markings[i],
  1588. xrange = extractRange(m, "x"),
  1589. yrange = extractRange(m, "y");
  1590. // fill in missing
  1591. if (xrange.from == null) {
  1592. xrange.from = xrange.axis.min;
  1593. }
  1594. if (xrange.to == null) {
  1595. xrange.to = xrange.axis.max;
  1596. }
  1597. if (yrange.from == null) {
  1598. yrange.from = yrange.axis.min;
  1599. }
  1600. if (yrange.to == null) {
  1601. yrange.to = yrange.axis.max;
  1602. }
  1603. // clip
  1604. if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
  1605. yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) {
  1606. continue;
  1607. }
  1608. xrange.from = Math.max(xrange.from, xrange.axis.min);
  1609. xrange.to = Math.min(xrange.to, xrange.axis.max);
  1610. yrange.from = Math.max(yrange.from, yrange.axis.min);
  1611. yrange.to = Math.min(yrange.to, yrange.axis.max);
  1612. var xequal = xrange.from === xrange.to,
  1613. yequal = yrange.from === yrange.to;
  1614. if (xequal && yequal) {
  1615. continue;
  1616. }
  1617. // then draw
  1618. xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
  1619. xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
  1620. yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
  1621. yrange.to = Math.floor(yrange.axis.p2c(yrange.to));
  1622. if (xequal || yequal) {
  1623. var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
  1624. subPixel = lineWidth % 2 ? 0.5 : 0;
  1625. ctx.beginPath();
  1626. ctx.strokeStyle = m.color || options.grid.markingsColor;
  1627. ctx.lineWidth = lineWidth;
  1628. if (xequal) {
  1629. ctx.moveTo(xrange.to + subPixel, yrange.from);
  1630. ctx.lineTo(xrange.to + subPixel, yrange.to);
  1631. } else {
  1632. ctx.moveTo(xrange.from, yrange.to + subPixel);
  1633. ctx.lineTo(xrange.to, yrange.to + subPixel);
  1634. }
  1635. ctx.stroke();
  1636. } else {
  1637. ctx.fillStyle = m.color || options.grid.markingsColor;
  1638. ctx.fillRect(xrange.from, yrange.to,
  1639. xrange.to - xrange.from,
  1640. yrange.from - yrange.to);
  1641. }
  1642. }
  1643. }
  1644. }
  1645. function findEdges(axis) {
  1646. var box = axis.box,
  1647. x = 0,
  1648. y = 0;
  1649. // find the edges
  1650. if (axis.direction === "x") {
  1651. x = 0;
  1652. y = box.top - plotOffset.top + (axis.position === "top" ? box.height : 0);
  1653. } else {
  1654. y = 0;
  1655. x = box.left - plotOffset.left + (axis.position === "left" ? box.width : 0) + axis.boxPosition.centerX;
  1656. }
  1657. return {
  1658. x: x,
  1659. y: y
  1660. };
  1661. };
  1662. function alignPosition(lineWidth, pos) {
  1663. return ((lineWidth % 2) !== 0) ? Math.floor(pos) + 0.5 : pos;
  1664. };
  1665. function drawTickBar(axis) {
  1666. ctx.lineWidth = 1;
  1667. var edges = findEdges(axis),
  1668. x = edges.x,
  1669. y = edges.y;
  1670. // draw tick bar
  1671. if (axis.show) {
  1672. var xoff = 0,
  1673. yoff = 0;
  1674. ctx.strokeStyle = axis.options.color;
  1675. ctx.beginPath();
  1676. if (axis.direction === "x") {
  1677. xoff = plotWidth + 1;
  1678. } else {
  1679. yoff = plotHeight + 1;
  1680. }
  1681. if (axis.direction === "x") {
  1682. y = alignPosition(ctx.lineWidth, y);
  1683. } else {
  1684. x = alignPosition(ctx.lineWidth, x);
  1685. }
  1686. ctx.moveTo(x, y);
  1687. ctx.lineTo(x + xoff, y + yoff);
  1688. ctx.stroke();
  1689. }
  1690. };
  1691. function drawTickMarks(axis) {
  1692. var t = axis.tickLength,
  1693. minorTicks = axis.showMinorTicks,
  1694. minorTicksNr = MINOR_TICKS_COUNT_CONSTANT,
  1695. edges = findEdges(axis),
  1696. x = edges.x,
  1697. y = edges.y,
  1698. i = 0;
  1699. // draw major tick marks
  1700. ctx.strokeStyle = axis.options.color;
  1701. ctx.beginPath();
  1702. for (i = 0; i < axis.ticks.length; ++i) {
  1703. var v = axis.ticks[i].v,
  1704. xoff = 0,
  1705. yoff = 0,
  1706. xminor = 0,
  1707. yminor = 0,
  1708. j;
  1709. if (!isNaN(v) && v >= axis.min && v <= axis.max) {
  1710. if (axis.direction === "x") {
  1711. x = axis.p2c(v);
  1712. yoff = t;
  1713. if (axis.position === "top") {
  1714. yoff = -yoff;
  1715. }
  1716. } else {
  1717. y = axis.p2c(v);
  1718. xoff = t;
  1719. if (axis.position === "left") {
  1720. xoff = -xoff;
  1721. }
  1722. }
  1723. if (axis.direction === "x") {
  1724. x = alignPosition(ctx.lineWidth, x);
  1725. } else {
  1726. y = alignPosition(ctx.lineWidth, y);
  1727. }
  1728. ctx.moveTo(x, y);
  1729. ctx.lineTo(x + xoff, y + yoff);
  1730. }
  1731. //draw minor tick marks
  1732. if (minorTicks === true && i < axis.ticks.length - 1) {
  1733. var v1 = axis.ticks[i].v,
  1734. v2 = axis.ticks[i + 1].v,
  1735. step = (v2 - v1) / (minorTicksNr + 1);
  1736. for (j = 1; j <= minorTicksNr; j++) {
  1737. // compute minor tick position
  1738. if (axis.direction === "x") {
  1739. yminor = t / 2; // minor ticks are half length
  1740. x = alignPosition(ctx.lineWidth, axis.p2c(v1 + j * step))
  1741. if (axis.position === "top") {
  1742. yminor = -yminor;
  1743. }
  1744. // don't go over the plot borders
  1745. if ((x < 0) || (x > plotWidth)) {
  1746. continue;
  1747. }
  1748. } else {
  1749. xminor = t / 2; // minor ticks are half length
  1750. y = alignPosition(ctx.lineWidth, axis.p2c(v1 + j * step));
  1751. if (axis.position === "left") {
  1752. xminor = -xminor;
  1753. }
  1754. // don't go over the plot borders
  1755. if ((y < 0) || (y > plotHeight)) {
  1756. continue;
  1757. }
  1758. }
  1759. ctx.moveTo(x, y);
  1760. ctx.lineTo(x + xminor, y + yminor);
  1761. }
  1762. }
  1763. }
  1764. ctx.stroke();
  1765. };
  1766. function drawGridLines(axis) {
  1767. // check if the line will be overlapped with a border
  1768. var overlappedWithBorder = function (value) {
  1769. var bw = options.grid.borderWidth;
  1770. return (((typeof bw === "object" && bw[axis.position] > 0) || bw > 0) && (value === axis.min || value === axis.max));
  1771. };
  1772. ctx.strokeStyle = options.grid.tickColor;
  1773. ctx.beginPath();
  1774. var i;
  1775. for (i = 0; i < axis.ticks.length; ++i) {
  1776. var v = axis.ticks[i].v,
  1777. xoff = 0,
  1778. yoff = 0,
  1779. x = 0,
  1780. y = 0;
  1781. if (isNaN(v) || v < axis.min || v > axis.max) continue;
  1782. // skip those lying on the axes if we got a border
  1783. if (overlappedWithBorder(v)) continue;
  1784. if (axis.direction === "x") {
  1785. x = axis.p2c(v);
  1786. y = plotHeight;
  1787. yoff = -plotHeight;
  1788. } else {
  1789. x = 0;
  1790. y = axis.p2c(v);
  1791. xoff = plotWidth;
  1792. }
  1793. if (axis.direction === "x") {
  1794. x = alignPosition(ctx.lineWidth, x);
  1795. } else {
  1796. y = alignPosition(ctx.lineWidth, y);
  1797. }
  1798. ctx.moveTo(x, y);
  1799. ctx.lineTo(x + xoff, y + yoff);
  1800. }
  1801. ctx.stroke();
  1802. };
  1803. function drawBorder() {
  1804. // If either borderWidth or borderColor is an object, then draw the border
  1805. // line by line instead of as one rectangle
  1806. var bw = options.grid.borderWidth,
  1807. bc = options.grid.borderColor;
  1808. if (typeof bw === "object" || typeof bc === "object") {
  1809. if (typeof bw !== "object") {
  1810. bw = {
  1811. top: bw,
  1812. right: bw,
  1813. bottom: bw,
  1814. left: bw
  1815. };
  1816. }
  1817. if (typeof bc !== "object") {
  1818. bc = {
  1819. top: bc,
  1820. right: bc,
  1821. bottom: bc,
  1822. left: bc
  1823. };
  1824. }
  1825. if (bw.top > 0) {
  1826. ctx.strokeStyle = bc.top;
  1827. ctx.lineWidth = bw.top;
  1828. ctx.beginPath();
  1829. ctx.moveTo(0 - bw.left, 0 - bw.top / 2);
  1830. ctx.lineTo(plotWidth, 0 - bw.top / 2);
  1831. ctx.stroke();
  1832. }
  1833. if (bw.right > 0) {
  1834. ctx.strokeStyle = bc.right;
  1835. ctx.lineWidth = bw.right;
  1836. ctx.beginPath();
  1837. ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
  1838. ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
  1839. ctx.stroke();
  1840. }
  1841. if (bw.bottom > 0) {
  1842. ctx.strokeStyle = bc.bottom;
  1843. ctx.lineWidth = bw.bottom;
  1844. ctx.beginPath();
  1845. ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
  1846. ctx.lineTo(0, plotHeight + bw.bottom / 2);
  1847. ctx.stroke();
  1848. }
  1849. if (bw.left > 0) {
  1850. ctx.strokeStyle = bc.left;
  1851. ctx.lineWidth = bw.left;
  1852. ctx.beginPath();
  1853. ctx.moveTo(0 - bw.left / 2, plotHeight + bw.bottom);
  1854. ctx.lineTo(0 - bw.left / 2, 0);
  1855. ctx.stroke();
  1856. }
  1857. } else {
  1858. ctx.lineWidth = bw;
  1859. ctx.strokeStyle = options.grid.borderColor;
  1860. ctx.strokeRect(-bw / 2, -bw / 2, plotWidth + bw, plotHeight + bw);
  1861. }
  1862. };
  1863. function drawGrid() {
  1864. var axes, bw;
  1865. ctx.save();
  1866. ctx.translate(plotOffset.left, plotOffset.top);
  1867. drawMarkings();
  1868. axes = allAxes();
  1869. bw = options.grid.borderWidth;
  1870. for (var j = 0; j < axes.length; ++j) {
  1871. var axis = axes[j];
  1872. if (!axis.show) {
  1873. continue;
  1874. }
  1875. drawTickBar(axis);
  1876. if (axis.showTicks === true) {
  1877. drawTickMarks(axis);
  1878. }
  1879. if (axis.gridLines === true) {
  1880. drawGridLines(axis, bw);
  1881. }
  1882. }
  1883. // draw border
  1884. if (bw) {
  1885. drawBorder();
  1886. }
  1887. ctx.restore();
  1888. }
  1889. function drawAxisLabels() {
  1890. $.each(allAxes(), function(_, axis) {
  1891. var box = axis.box,
  1892. legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
  1893. layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
  1894. font = axis.options.font || "flot-tick-label tickLabel",
  1895. i, x, y, halign, valign, info,
  1896. margin = 3,
  1897. nullBox = {x: NaN, y: NaN, width: NaN, height: NaN}, newLabelBox, labelBoxes = [],
  1898. overlapping = function(x11, y11, x12, y12, x21, y21, x22, y22) {
  1899. return ((x11 <= x21 && x21 <= x12) || (x21 <= x11 && x11 <= x22)) &&
  1900. ((y11 <= y21 && y21 <= y12) || (y21 <= y11 && y11 <= y22));
  1901. },
  1902. overlapsOtherLabels = function(newLabelBox, previousLabelBoxes) {
  1903. return previousLabelBoxes.some(function(labelBox) {
  1904. return overlapping(
  1905. newLabelBox.x, newLabelBox.y, newLabelBox.x + newLabelBox.width, newLabelBox.y + newLabelBox.height,
  1906. labelBox.x, labelBox.y, labelBox.x + labelBox.width, labelBox.y + labelBox.height);
  1907. });
  1908. },
  1909. drawAxisLabel = function (tick, labelBoxes) {
  1910. if (!tick || !tick.label || tick.v < axis.min || tick.v > axis.max) {
  1911. return nullBox;
  1912. }
  1913. info = surface.getTextInfo(layer, tick.label, font);
  1914. if (axis.direction === "x") {
  1915. halign = "center";
  1916. x = plotOffset.left + axis.p2c(tick.v);
  1917. if (axis.position === "bottom") {
  1918. y = box.top + box.padding - axis.boxPosition.centerY;
  1919. } else {
  1920. y = box.top + box.height - box.padding + axis.boxPosition.centerY;
  1921. valign = "bottom";
  1922. }
  1923. newLabelBox = {x: x - info.width / 2 - margin, y: y - margin, width: info.width + 2 * margin, height: info.height + 2 * margin};
  1924. } else {
  1925. valign = "middle";
  1926. y = plotOffset.top + axis.p2c(tick.v);
  1927. if (axis.position === "left") {
  1928. x = box.left + box.width - box.padding - axis.boxPosition.centerX;
  1929. halign = "right";
  1930. } else {
  1931. x = box.left + box.padding + axis.boxPosition.centerX;
  1932. }
  1933. newLabelBox = {x: x - info.width / 2 - margin, y: y - margin, width: info.width + 2 * margin, height: info.height + 2 * margin};
  1934. }
  1935. if (overlapsOtherLabels(newLabelBox, labelBoxes)) {
  1936. return nullBox;
  1937. }
  1938. surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
  1939. return newLabelBox;
  1940. };
  1941. // Remove text before checking for axis.show and ticks.length;
  1942. // otherwise plugins, like flot-tickrotor, that draw their own
  1943. // tick labels will end up with both theirs and the defaults.
  1944. surface.removeText(layer);
  1945. executeHooks(hooks.drawAxis, [axis, surface]);
  1946. if (!axis.show) {
  1947. return;
  1948. }
  1949. switch (axis.options.showTickLabels) {
  1950. case 'none':
  1951. break;
  1952. case 'endpoints':
  1953. labelBoxes.push(drawAxisLabel(axis.ticks[0], labelBoxes));
  1954. labelBoxes.push(drawAxisLabel(axis.ticks[axis.ticks.length - 1], labelBoxes));
  1955. break;
  1956. case 'major':
  1957. labelBoxes.push(drawAxisLabel(axis.ticks[0], labelBoxes));
  1958. labelBoxes.push(drawAxisLabel(axis.ticks[axis.ticks.length - 1], labelBoxes));
  1959. for (i = 1; i < axis.ticks.length - 1; ++i) {
  1960. labelBoxes.push(drawAxisLabel(axis.ticks[i], labelBoxes));
  1961. }
  1962. break;
  1963. case 'all':
  1964. labelBoxes.push(drawAxisLabel(axis.ticks[0], []));
  1965. labelBoxes.push(drawAxisLabel(axis.ticks[axis.ticks.length - 1], labelBoxes));
  1966. for (i = 1; i < axis.ticks.length - 1; ++i) {
  1967. labelBoxes.push(drawAxisLabel(axis.ticks[i], labelBoxes));
  1968. }
  1969. break;
  1970. }
  1971. });
  1972. }
  1973. function drawSeries(series) {
  1974. if (series.lines.show) {
  1975. $.plot.drawSeries.drawSeriesLines(series, ctx, plotOffset, plotWidth, plotHeight, plot.drawSymbol, getColorOrGradient);
  1976. }
  1977. if (series.bars.show) {
  1978. $.plot.drawSeries.drawSeriesBars(series, ctx, plotOffset, plotWidth, plotHeight, plot.drawSymbol, getColorOrGradient);
  1979. }
  1980. if (series.points.show) {
  1981. $.plot.drawSeries.drawSeriesPoints(series, ctx, plotOffset, plotWidth, plotHeight, plot.drawSymbol, getColorOrGradient);
  1982. }
  1983. }
  1984. function computeRangeForDataSeries(series, force, isValid) {
  1985. var points = series.datapoints.points,
  1986. ps = series.datapoints.pointsize,
  1987. format = series.datapoints.format,
  1988. topSentry = Number.POSITIVE_INFINITY,
  1989. bottomSentry = Number.NEGATIVE_INFINITY,
  1990. range = {
  1991. xmin: topSentry,
  1992. ymin: topSentry,
  1993. xmax: bottomSentry,
  1994. ymax: bottomSentry
  1995. };
  1996. for (var j = 0; j < points.length; j += ps) {
  1997. if (points[j] === null) {
  1998. continue;
  1999. }
  2000. if (typeof (isValid) === 'function' && !isValid(points[j])) {
  2001. continue;
  2002. }
  2003. for (var m = 0; m < ps; ++m) {
  2004. var val = points[j + m],
  2005. f = format[m];
  2006. if (f === null || f === undefined) {
  2007. continue;
  2008. }
  2009. if (typeof (isValid) === 'function' && !isValid(val)) {
  2010. continue;
  2011. }
  2012. if ((!force && !f.computeRange) || val === Infinity || val === -Infinity) {
  2013. continue;
  2014. }
  2015. if (f.x === true) {
  2016. if (val < range.xmin) {
  2017. range.xmin = val;
  2018. }
  2019. if (val > range.xmax) {
  2020. range.xmax = val;
  2021. }
  2022. }
  2023. if (f.y === true) {
  2024. if (val < range.ymin) {
  2025. range.ymin = val;
  2026. }
  2027. if (val > range.ymax) {
  2028. range.ymax = val;
  2029. }
  2030. }
  2031. }
  2032. }
  2033. return range;
  2034. };
  2035. function adjustSeriesDataRange(series, range) {
  2036. if (series.bars.show) {
  2037. // make sure we got room for the bar on the dancing floor
  2038. var delta;
  2039. // update bar width if needed
  2040. var useAbsoluteBarWidth = series.bars.barWidth[1];
  2041. if (series.datapoints && series.datapoints.points && !useAbsoluteBarWidth) {
  2042. computeBarWidth(series);
  2043. }
  2044. var barWidth = series.bars.barWidth[0] || series.bars.barWidth;
  2045. switch (series.bars.align) {
  2046. case "left":
  2047. delta = 0;
  2048. break;
  2049. case "right":
  2050. delta = -barWidth;
  2051. break;
  2052. default:
  2053. delta = -barWidth / 2;
  2054. }
  2055. if (series.bars.horizontal) {
  2056. range.ymin += delta;
  2057. range.ymax += delta + barWidth;
  2058. }
  2059. else {
  2060. range.xmin += delta;
  2061. range.xmax += delta + barWidth;
  2062. }
  2063. }
  2064. if ((series.bars.show && series.bars.zero) || (series.lines.show && series.lines.zero)) {
  2065. var ps = series.datapoints.pointsize;
  2066. // make sure the 0 point is included in the computed y range when requested
  2067. if (ps <= 2) {
  2068. /*if ps > 0 the points were already taken into account for autoScale */
  2069. range.ymin = Math.min(0, range.ymin);
  2070. range.ymax = Math.max(0, range.ymax);
  2071. }
  2072. }
  2073. return range;
  2074. };
  2075. function computeBarWidth(series) {
  2076. var pointsize = series.datapoints.pointsize, minDistance = Number.MAX_VALUE,
  2077. distance = series.datapoints.points[pointsize] - series.datapoints.points[0] || 1;
  2078. if (isFinite(distance)) {
  2079. minDistance = distance;
  2080. }
  2081. for (var j = pointsize; j < series.datapoints.points.length - pointsize; j += pointsize) {
  2082. distance = Math.abs(series.datapoints.points[pointsize + j] - series.datapoints.points[j]);
  2083. if (distance < minDistance && isFinite(distance)) {
  2084. minDistance = distance;
  2085. }
  2086. }
  2087. if (typeof series.bars.barWidth === "number") {
  2088. series.bars.barWidth = series.bars.barWidth * minDistance;
  2089. } else {
  2090. series.bars.barWidth[0] = series.bars.barWidth[0] * minDistance;
  2091. }
  2092. }
  2093. // returns the data item the mouse is over/ the cursor is closest to, or null if none is found
  2094. function findNearbyItem(mouseX, mouseY, seriesFilter, radius, computeDistance) {
  2095. var i, j,
  2096. item = null,
  2097. smallestDistance = radius * radius + 1;
  2098. for (var i = series.length - 1; i >= 0; --i) {
  2099. if (!seriesFilter(i)) continue;
  2100. var s = series[i];
  2101. if (!s.datapoints) return;
  2102. if (s.lines.show || s.points.show) {
  2103. var found = findNearbyPoint(s, mouseX, mouseY, radius, smallestDistance, computeDistance);
  2104. if (found) {
  2105. smallestDistance = found.distance;
  2106. item = [i, found.dataIndex];
  2107. }
  2108. }
  2109. if (s.bars.show && !item) { // no other point can be nearby
  2110. var foundIndex = findNearbyBar(s, mouseX, mouseY);
  2111. if (foundIndex) item = [i, foundIndex];
  2112. }
  2113. }
  2114. if (item) {
  2115. i = item[0];
  2116. j = item[1];
  2117. var ps = series[i].datapoints.pointsize;
  2118. return {
  2119. datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
  2120. dataIndex: j,
  2121. series: series[i],
  2122. seriesIndex: i
  2123. };
  2124. }
  2125. return null;
  2126. }
  2127. function findNearbyPoint (series, mouseX, mouseY, maxDistance, smallestDistance, computeDistance) {
  2128. var mx = series.xaxis.c2p(mouseX),
  2129. my = series.yaxis.c2p(mouseY),
  2130. maxx = maxDistance / series.xaxis.scale,
  2131. maxy = maxDistance / series.yaxis.scale,
  2132. points = series.datapoints.points,
  2133. ps = series.datapoints.pointsize;
  2134. // with inverse transforms, we can't use the maxx/maxy
  2135. // optimization, sadly
  2136. if (series.xaxis.options.inverseTransform) {
  2137. maxx = Number.MAX_VALUE;
  2138. }
  2139. if (series.yaxis.options.inverseTransform) {
  2140. maxy = Number.MAX_VALUE;
  2141. }
  2142. var found = null;
  2143. for (var j = 0; j < points.length; j += ps) {
  2144. var x = points[j];
  2145. var y = points[j + 1];
  2146. if (x == null) {
  2147. continue;
  2148. }
  2149. if (x - mx > maxx || x - mx < -maxx ||
  2150. y - my > maxy || y - my < -maxy) {
  2151. continue;
  2152. }
  2153. // We have to calculate distances in pixels, not in
  2154. // data units, because the scales of the axes may be different
  2155. var dx = Math.abs(series.xaxis.p2c(x) - mouseX);
  2156. var dy = Math.abs(series.yaxis.p2c(y) - mouseY);
  2157. var dist = computeDistance ? computeDistance(dx, dy) : dx * dx + dy * dy;
  2158. // use <= to ensure last point takes precedence
  2159. // (last generally means on top of)
  2160. if (dist < smallestDistance) {
  2161. smallestDistance = dist;
  2162. found = { dataIndex: j / ps, distance: dist };
  2163. }
  2164. }
  2165. return found;
  2166. }
  2167. function findNearbyBar (series, mouseX, mouseY) {
  2168. var barLeft, barRight,
  2169. barWidth = series.bars.barWidth[0] || series.bars.barWidth,
  2170. mx = series.xaxis.c2p(mouseX),
  2171. my = series.yaxis.c2p(mouseY),
  2172. points = series.datapoints.points,
  2173. ps = series.datapoints.pointsize;
  2174. switch (series.bars.align) {
  2175. case "left":
  2176. barLeft = 0;
  2177. break;
  2178. case "right":
  2179. barLeft = -barWidth;
  2180. break;
  2181. default:
  2182. barLeft = -barWidth / 2;
  2183. }
  2184. barRight = barLeft + barWidth;
  2185. var fillTowards = series.bars.fillTowards || 0;
  2186. var bottom = fillTowards > series.yaxis.min ? Math.min(series.yaxis.max, fillTowards) : series.yaxis.min;
  2187. var foundIndex = null;
  2188. for (var j = 0; j < points.length; j += ps) {
  2189. var x = points[j], y = points[j + 1];
  2190. if (x == null)
  2191. continue;
  2192. // for a bar graph, the cursor must be inside the bar
  2193. if (series.bars.horizontal ?
  2194. (mx <= Math.max(bottom, x) && mx >= Math.min(bottom, x) &&
  2195. my >= y + barLeft && my <= y + barRight) :
  2196. (mx >= x + barLeft && mx <= x + barRight &&
  2197. my >= Math.min(bottom, y) && my <= Math.max(bottom, y)))
  2198. foundIndex = j / ps;
  2199. }
  2200. return foundIndex;
  2201. }
  2202. function findNearbyInterpolationPoint(posX, posY, seriesFilter) {
  2203. var i, j, dist, dx, dy, ps,
  2204. item,
  2205. smallestDistance = Number.MAX_VALUE;
  2206. for (i = 0; i < series.length; ++i) {
  2207. if (!seriesFilter(i)) {
  2208. continue;
  2209. }
  2210. var points = series[i].datapoints.points;
  2211. ps = series[i].datapoints.pointsize;
  2212. // if the data is coming from positive -> negative, reverse the comparison
  2213. const comparer = points[points.length - ps] < points[0]
  2214. ? function (x1, x2) { return x1 > x2 }
  2215. : function (x1, x2) { return x2 > x1 };
  2216. // do not interpolate outside the bounds of the data.
  2217. if (comparer(posX, points[0])) {
  2218. continue;
  2219. }
  2220. // Find the nearest points, x-wise
  2221. for (j = ps; j < points.length; j += ps) {
  2222. if (comparer(posX, points[j])) {
  2223. break;
  2224. }
  2225. }
  2226. // Now Interpolate
  2227. var y,
  2228. p1x = points[j - ps],
  2229. p1y = points[j - ps + 1],
  2230. p2x = points[j],
  2231. p2y = points[j + 1];
  2232. if ((p1x === undefined) || (p2x === undefined) ||
  2233. (p1y === undefined) || (p2y === undefined)) {
  2234. continue;
  2235. }
  2236. if (p1x === p2x) {
  2237. y = p2y
  2238. } else {
  2239. y = p1y + (p2y - p1y) * (posX - p1x) / (p2x - p1x);
  2240. }
  2241. posY = y;
  2242. dx = Math.abs(series[i].xaxis.p2c(p2x) - posX);
  2243. dy = Math.abs(series[i].yaxis.p2c(p2y) - posY);
  2244. dist = dx * dx + dy * dy;
  2245. if (dist < smallestDistance) {
  2246. smallestDistance = dist;
  2247. item = [posX, posY, i, j];
  2248. }
  2249. }
  2250. if (item) {
  2251. i = item[2];
  2252. j = item[3];
  2253. ps = series[i].datapoints.pointsize;
  2254. points = series[i].datapoints.points;
  2255. p1x = points[j - ps];
  2256. p1y = points[j - ps + 1];
  2257. p2x = points[j];
  2258. p2y = points[j + 1];
  2259. return {
  2260. datapoint: [item[0], item[1]],
  2261. leftPoint: [p1x, p1y],
  2262. rightPoint: [p2x, p2y],
  2263. seriesIndex: i
  2264. };
  2265. }
  2266. return null;
  2267. }
  2268. function triggerRedrawOverlay() {
  2269. var t = options.interaction.redrawOverlayInterval;
  2270. if (t === -1) { // skip event queue
  2271. drawOverlay();
  2272. return;
  2273. }
  2274. if (!redrawTimeout) {
  2275. redrawTimeout = setTimeout(function() {
  2276. drawOverlay(plot);
  2277. }, t);
  2278. }
  2279. }
  2280. function drawOverlay(plot) {
  2281. redrawTimeout = null;
  2282. if (!octx) {
  2283. return;
  2284. }
  2285. overlay.clear();
  2286. executeHooks(hooks.drawOverlay, [octx, overlay]);
  2287. var event = new CustomEvent('onDrawingDone');
  2288. plot.getEventHolder().dispatchEvent(event);
  2289. }
  2290. function getColorOrGradient(spec, bottom, top, defaultColor) {
  2291. if (typeof spec === "string") {
  2292. return spec;
  2293. } else {
  2294. // assume this is a gradient spec; IE currently only
  2295. // supports a simple vertical gradient properly, so that's
  2296. // what we support too
  2297. var gradient = ctx.createLinearGradient(0, top, 0, bottom);
  2298. for (var i = 0, l = spec.colors.length; i < l; ++i) {
  2299. var c = spec.colors[i];
  2300. if (typeof c !== "string") {
  2301. var co = $.color.parse(defaultColor);
  2302. if (c.brightness != null) {
  2303. co = co.scale('rgb', c.brightness);
  2304. }
  2305. if (c.opacity != null) {
  2306. co.a *= c.opacity;
  2307. }
  2308. c = co.toString();
  2309. }
  2310. gradient.addColorStop(i / (l - 1), c);
  2311. }
  2312. return gradient;
  2313. }
  2314. }
  2315. }
  2316. // Add the plot function to the top level of the jQuery object
  2317. $.plot = function(placeholder, data, options) {
  2318. var plot = new Plot($(placeholder), data, options, $.plot.plugins);
  2319. return plot;
  2320. };
  2321. $.plot.version = "1.0.3";
  2322. $.plot.plugins = [];
  2323. // Also add the plot function as a chainable property
  2324. $.fn.plot = function(data, options) {
  2325. return this.each(function() {
  2326. $.plot(this, data, options);
  2327. });
  2328. };
  2329. $.plot.linearTickGenerator = defaultTickGenerator;
  2330. $.plot.defaultTickFormatter = defaultTickFormatter;
  2331. $.plot.expRepTickFormatter = expRepTickFormatter;
  2332. })(jQuery);