flot-charts.min.js 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222
  1. /* Javascript plotting library for jQuery, version 0.8.3.
  2. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3. Licensed under the MIT license.
  4. */
  5. // first an inline dependency, jquery.colorhelpers.js, we inline it here
  6. // for convenience
  7. /* Plugin for jQuery for working with colors.
  8. *
  9. * Version 1.1.
  10. *
  11. * Inspiration from jQuery color animation plugin by John Resig.
  12. *
  13. * Released under the MIT license by Ole Laursen, October 2009.
  14. *
  15. * Examples:
  16. *
  17. * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
  18. * var c = $.color.extract($("#mydiv"), 'background-color');
  19. * console.log(c.r, c.g, c.b, c.a);
  20. * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
  21. *
  22. * Note that .scale() and .add() return the same modified object
  23. * instead of making a new one.
  24. *
  25. * V. 1.1: Fix error handling so e.g. parsing an empty string does
  26. * produce a color rather than just crashing.
  27. */
  28. (function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
  29. // the actual Flot code
  30. (function($) {
  31. // Cache the prototype hasOwnProperty for faster access
  32. var hasOwnProperty = Object.prototype.hasOwnProperty;
  33. // A shim to provide 'detach' to jQuery versions prior to 1.4. Using a DOM
  34. // operation produces the same effect as detach, i.e. removing the element
  35. // without touching its jQuery data.
  36. // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.
  37. if (!$.fn.detach) {
  38. $.fn.detach = function() {
  39. return this.each(function() {
  40. if (this.parentNode) {
  41. this.parentNode.removeChild( this );
  42. }
  43. });
  44. };
  45. }
  46. ///////////////////////////////////////////////////////////////////////////
  47. // The Canvas object is a wrapper around an HTML5 <canvas> tag.
  48. //
  49. // @constructor
  50. // @param {string} cls List of classes to apply to the canvas.
  51. // @param {element} container Element onto which to append the canvas.
  52. //
  53. // Requiring a container is a little iffy, but unfortunately canvas
  54. // operations don't work unless the canvas is attached to the DOM.
  55. function Canvas(cls, container) {
  56. var element = container.children("." + cls)[0];
  57. if (element == null) {
  58. element = document.createElement("canvas");
  59. element.className = cls;
  60. $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
  61. .appendTo(container);
  62. // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
  63. if (!element.getContext) {
  64. if (window.G_vmlCanvasManager) {
  65. element = window.G_vmlCanvasManager.initElement(element);
  66. } else {
  67. throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
  68. }
  69. }
  70. }
  71. this.element = element;
  72. var context = this.context = element.getContext("2d");
  73. // Determine the screen's ratio of physical to device-independent
  74. // pixels. This is the ratio between the canvas width that the browser
  75. // advertises and the number of pixels actually present in that space.
  76. // The iPhone 4, for example, has a device-independent width of 320px,
  77. // but its screen is actually 640px wide. It therefore has a pixel
  78. // ratio of 2, while most normal devices have a ratio of 1.
  79. var devicePixelRatio = window.devicePixelRatio || 1,
  80. backingStoreRatio =
  81. context.webkitBackingStorePixelRatio ||
  82. context.mozBackingStorePixelRatio ||
  83. context.msBackingStorePixelRatio ||
  84. context.oBackingStorePixelRatio ||
  85. context.backingStorePixelRatio || 1;
  86. this.pixelRatio = devicePixelRatio / backingStoreRatio;
  87. // Size the canvas to match the internal dimensions of its container
  88. this.resize(container.width(), container.height());
  89. // Collection of HTML div layers for text overlaid onto the canvas
  90. this.textContainer = null;
  91. this.text = {};
  92. // Cache of text fragments and metrics, so we can avoid expensively
  93. // re-calculating them when the plot is re-rendered in a loop.
  94. this._textCache = {};
  95. }
  96. // Resizes the canvas to the given dimensions.
  97. //
  98. // @param {number} width New width of the canvas, in pixels.
  99. // @param {number} width New height of the canvas, in pixels.
  100. Canvas.prototype.resize = function(width, height) {
  101. if (width <= 0 || height <= 0) {
  102. throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
  103. }
  104. var element = this.element,
  105. context = this.context,
  106. pixelRatio = this.pixelRatio;
  107. // Resize the canvas, increasing its density based on the display's
  108. // pixel ratio; basically giving it more pixels without increasing the
  109. // size of its element, to take advantage of the fact that retina
  110. // displays have that many more pixels in the same advertised space.
  111. // Resizing should reset the state (excanvas seems to be buggy though)
  112. if (this.width != width) {
  113. element.width = width * pixelRatio;
  114. element.style.width = width + "px";
  115. this.width = width;
  116. }
  117. if (this.height != height) {
  118. element.height = height * pixelRatio;
  119. element.style.height = height + "px";
  120. this.height = height;
  121. }
  122. // Save the context, so we can reset in case we get replotted. The
  123. // restore ensure that we're really back at the initial state, and
  124. // should be safe even if we haven't saved the initial state yet.
  125. context.restore();
  126. context.save();
  127. // Scale the coordinate space to match the display density; so even though we
  128. // may have twice as many pixels, we still want lines and other drawing to
  129. // appear at the same size; the extra pixels will just make them crisper.
  130. context.scale(pixelRatio, pixelRatio);
  131. };
  132. // Clears the entire canvas area, not including any overlaid HTML text
  133. Canvas.prototype.clear = function() {
  134. this.context.clearRect(0, 0, this.width, this.height);
  135. };
  136. // Finishes rendering the canvas, including managing the text overlay.
  137. Canvas.prototype.render = function() {
  138. var cache = this._textCache;
  139. // For each text layer, add elements marked as active that haven't
  140. // already been rendered, and remove those that are no longer active.
  141. for (var layerKey in cache) {
  142. if (hasOwnProperty.call(cache, layerKey)) {
  143. var layer = this.getTextLayer(layerKey),
  144. layerCache = cache[layerKey];
  145. layer.hide();
  146. for (var styleKey in layerCache) {
  147. if (hasOwnProperty.call(layerCache, styleKey)) {
  148. var styleCache = layerCache[styleKey];
  149. for (var key in styleCache) {
  150. if (hasOwnProperty.call(styleCache, key)) {
  151. var positions = styleCache[key].positions;
  152. for (var i = 0, position; position = positions[i]; i++) {
  153. if (position.active) {
  154. if (!position.rendered) {
  155. layer.append(position.element);
  156. position.rendered = true;
  157. }
  158. } else {
  159. positions.splice(i--, 1);
  160. if (position.rendered) {
  161. position.element.detach();
  162. }
  163. }
  164. }
  165. if (positions.length == 0) {
  166. delete styleCache[key];
  167. }
  168. }
  169. }
  170. }
  171. }
  172. layer.show();
  173. }
  174. }
  175. };
  176. // Creates (if necessary) and returns the text overlay container.
  177. //
  178. // @param {string} classes String of space-separated CSS classes used to
  179. // uniquely identify the text layer.
  180. // @return {object} The jQuery-wrapped text-layer div.
  181. Canvas.prototype.getTextLayer = function(classes) {
  182. var layer = this.text[classes];
  183. // Create the text layer if it doesn't exist
  184. if (layer == null) {
  185. // Create the text layer container, if it doesn't exist
  186. if (this.textContainer == null) {
  187. this.textContainer = $("<div class='flot-text'></div>")
  188. .css({
  189. position: "absolute",
  190. top: 0,
  191. left: 0,
  192. bottom: 0,
  193. right: 0,
  194. 'font-size': "smaller",
  195. color: "#545454"
  196. })
  197. .insertAfter(this.element);
  198. }
  199. layer = this.text[classes] = $("<div></div>")
  200. .addClass(classes)
  201. .css({
  202. position: "absolute",
  203. top: 0,
  204. left: 0,
  205. bottom: 0,
  206. right: 0
  207. })
  208. .appendTo(this.textContainer);
  209. }
  210. return layer;
  211. };
  212. // Creates (if necessary) and returns a text info object.
  213. //
  214. // The object looks like this:
  215. //
  216. // {
  217. // width: Width of the text's wrapper div.
  218. // height: Height of the text's wrapper div.
  219. // element: The jQuery-wrapped HTML div containing the text.
  220. // positions: Array of positions at which this text is drawn.
  221. // }
  222. //
  223. // The positions array contains objects that look like this:
  224. //
  225. // {
  226. // active: Flag indicating whether the text should be visible.
  227. // rendered: Flag indicating whether the text is currently visible.
  228. // element: The jQuery-wrapped HTML div containing the text.
  229. // x: X coordinate at which to draw the text.
  230. // y: Y coordinate at which to draw the text.
  231. // }
  232. //
  233. // Each position after the first receives a clone of the original element.
  234. //
  235. // The idea is that that the width, height, and general 'identity' of the
  236. // text is constant no matter where it is placed; the placements are a
  237. // secondary property.
  238. //
  239. // Canvas maintains a cache of recently-used text info objects; getTextInfo
  240. // either returns the cached element or creates a new entry.
  241. //
  242. // @param {string} layer A string of space-separated CSS classes uniquely
  243. // identifying the layer containing this text.
  244. // @param {string} text Text string to retrieve info for.
  245. // @param {(string|object)=} font Either a string of space-separated CSS
  246. // classes or a font-spec object, defining the text's font and style.
  247. // @param {number=} angle Angle at which to rotate the text, in degrees.
  248. // Angle is currently unused, it will be implemented in the future.
  249. // @param {number=} width Maximum width of the text before it wraps.
  250. // @return {object} a text info object.
  251. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
  252. var textStyle, layerCache, styleCache, info;
  253. // Cast the value to a string, in case we were given a number or such
  254. text = "" + text;
  255. // If the font is a font-spec object, generate a CSS font definition
  256. if (typeof font === "object") {
  257. textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
  258. } else {
  259. textStyle = font;
  260. }
  261. // Retrieve (or create) the cache for the text's layer and styles
  262. layerCache = this._textCache[layer];
  263. if (layerCache == null) {
  264. layerCache = this._textCache[layer] = {};
  265. }
  266. styleCache = layerCache[textStyle];
  267. if (styleCache == null) {
  268. styleCache = layerCache[textStyle] = {};
  269. }
  270. info = styleCache[text];
  271. // If we can't find a matching element in our cache, create a new one
  272. if (info == null) {
  273. var element = $("<div></div>").html(text)
  274. .css({
  275. position: "absolute",
  276. 'max-width': width,
  277. top: -9999
  278. })
  279. .appendTo(this.getTextLayer(layer));
  280. if (typeof font === "object") {
  281. element.css({
  282. font: textStyle,
  283. color: font.color
  284. });
  285. } else if (typeof font === "string") {
  286. element.addClass(font);
  287. }
  288. info = styleCache[text] = {
  289. width: element.outerWidth(true),
  290. height: element.outerHeight(true),
  291. element: element,
  292. positions: []
  293. };
  294. element.detach();
  295. }
  296. return info;
  297. };
  298. // Adds a text string to the canvas text overlay.
  299. //
  300. // The text isn't drawn immediately; it is marked as rendering, which will
  301. // result in its addition to the canvas on the next render pass.
  302. //
  303. // @param {string} layer A string of space-separated CSS classes uniquely
  304. // identifying the layer containing this text.
  305. // @param {number} x X coordinate at which to draw the text.
  306. // @param {number} y Y coordinate at which to draw the text.
  307. // @param {string} text Text string to draw.
  308. // @param {(string|object)=} font Either a string of space-separated CSS
  309. // classes or a font-spec object, defining the text's font and style.
  310. // @param {number=} angle Angle at which to rotate the text, in degrees.
  311. // Angle is currently unused, it will be implemented in the future.
  312. // @param {number=} width Maximum width of the text before it wraps.
  313. // @param {string=} halign Horizontal alignment of the text; either "left",
  314. // "center" or "right".
  315. // @param {string=} valign Vertical alignment of the text; either "top",
  316. // "middle" or "bottom".
  317. Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
  318. var info = this.getTextInfo(layer, text, font, angle, width),
  319. positions = info.positions;
  320. // Tweak the div's position to match the text's alignment
  321. if (halign == "center") {
  322. x -= info.width / 2;
  323. } else if (halign == "right") {
  324. x -= info.width;
  325. }
  326. if (valign == "middle") {
  327. y -= info.height / 2;
  328. } else if (valign == "bottom") {
  329. y -= info.height;
  330. }
  331. // Determine whether this text already exists at this position.
  332. // If so, mark it for inclusion in the next render pass.
  333. for (var i = 0, position; position = positions[i]; i++) {
  334. if (position.x == x && position.y == y) {
  335. position.active = true;
  336. return;
  337. }
  338. }
  339. // If the text doesn't exist at this position, create a new entry
  340. // For the very first position we'll re-use the original element,
  341. // while for subsequent ones we'll clone it.
  342. position = {
  343. active: true,
  344. rendered: false,
  345. element: positions.length ? info.element.clone() : info.element,
  346. x: x,
  347. y: y
  348. };
  349. positions.push(position);
  350. // Move the element to its final position within the container
  351. position.element.css({
  352. top: Math.round(y),
  353. left: Math.round(x),
  354. 'text-align': halign // In case the text wraps
  355. });
  356. };
  357. // Removes one or more text strings from the canvas text overlay.
  358. //
  359. // If no parameters are given, all text within the layer is removed.
  360. //
  361. // Note that the text is not immediately removed; it is simply marked as
  362. // inactive, which will result in its removal on the next render pass.
  363. // This avoids the performance penalty for 'clear and redraw' behavior,
  364. // where we potentially get rid of all text on a layer, but will likely
  365. // add back most or all of it later, as when redrawing axes, for example.
  366. //
  367. // @param {string} layer A string of space-separated CSS classes uniquely
  368. // identifying the layer containing this text.
  369. // @param {number=} x X coordinate of the text.
  370. // @param {number=} y Y coordinate of the text.
  371. // @param {string=} text Text string to remove.
  372. // @param {(string|object)=} font Either a string of space-separated CSS
  373. // classes or a font-spec object, defining the text's font and style.
  374. // @param {number=} angle Angle at which the text is rotated, in degrees.
  375. // Angle is currently unused, it will be implemented in the future.
  376. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
  377. if (text == null) {
  378. var layerCache = this._textCache[layer];
  379. if (layerCache != null) {
  380. for (var styleKey in layerCache) {
  381. if (hasOwnProperty.call(layerCache, styleKey)) {
  382. var styleCache = layerCache[styleKey];
  383. for (var key in styleCache) {
  384. if (hasOwnProperty.call(styleCache, key)) {
  385. var positions = styleCache[key].positions;
  386. for (var i = 0, position; position = positions[i]; i++) {
  387. position.active = false;
  388. }
  389. }
  390. }
  391. }
  392. }
  393. }
  394. } else {
  395. var positions = this.getTextInfo(layer, text, font, angle).positions;
  396. for (var i = 0, position; position = positions[i]; i++) {
  397. if (position.x == x && position.y == y) {
  398. position.active = false;
  399. }
  400. }
  401. }
  402. };
  403. ///////////////////////////////////////////////////////////////////////////
  404. // The top-level container for the entire plot.
  405. function Plot(placeholder, data_, options_, plugins) {
  406. // data is on the form:
  407. // [ series1, series2 ... ]
  408. // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
  409. // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
  410. var series = [],
  411. options = {
  412. // the color theme used for graphs
  413. colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
  414. legend: {
  415. show: true,
  416. noColumns: 1, // number of colums in legend table
  417. labelFormatter: null, // fn: string -> string
  418. labelBoxBorderColor: "#ccc", // border color for the little label boxes
  419. container: null, // container (as jQuery object) to put legend in, null means default on top of graph
  420. position: "ne", // position of default legend container within plot
  421. margin: 5, // distance from grid edge to default legend container within plot
  422. backgroundColor: null, // null means auto-detect
  423. backgroundOpacity: 0.85, // set to 0 to avoid background
  424. sorted: null // default to no legend sorting
  425. },
  426. xaxis: {
  427. show: null, // null = auto-detect, true = always, false = never
  428. position: "bottom", // or "top"
  429. mode: null, // null or "time"
  430. 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" }
  431. color: null, // base color, labels, ticks
  432. tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
  433. transform: null, // null or f: number -> number to transform axis
  434. inverseTransform: null, // if transform is set, this should be the inverse function
  435. min: null, // min. value to show, null means set automatically
  436. max: null, // max. value to show, null means set automatically
  437. autoscaleMargin: null, // margin in % to add if auto-setting min/max
  438. ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
  439. tickFormatter: null, // fn: number -> string
  440. labelWidth: null, // size of tick labels in pixels
  441. labelHeight: null,
  442. reserveSpace: null, // whether to reserve space even if axis isn't shown
  443. tickLength: null, // size in pixels of ticks, or "full" for whole line
  444. alignTicksWithAxis: null, // axis number or null for no sync
  445. tickDecimals: null, // no. of decimals, null means auto
  446. tickSize: null, // number or [number, "unit"]
  447. minTickSize: null // number or [number, "unit"]
  448. },
  449. yaxis: {
  450. autoscaleMargin: 0.02,
  451. position: "left" // or "right"
  452. },
  453. xaxes: [],
  454. yaxes: [],
  455. series: {
  456. points: {
  457. show: false,
  458. radius: 3,
  459. lineWidth: 2, // in pixels
  460. fill: true,
  461. fillColor: "#ffffff",
  462. symbol: "circle" // or callback
  463. },
  464. lines: {
  465. // we don't put in show: false so we can see
  466. // whether lines were actively disabled
  467. lineWidth: 2, // in pixels
  468. fill: false,
  469. fillColor: null,
  470. steps: false
  471. // Omit 'zero', so we can later default its value to
  472. // match that of the 'fill' option.
  473. },
  474. bars: {
  475. show: false,
  476. lineWidth: 2, // in pixels
  477. barWidth: 1, // in units of the x axis
  478. fill: true,
  479. fillColor: null,
  480. align: "left", // "left", "right", or "center"
  481. horizontal: false,
  482. zero: true
  483. },
  484. shadowSize: 3,
  485. highlightColor: null
  486. },
  487. grid: {
  488. show: true,
  489. aboveData: false,
  490. color: "#545454", // primary color used for outline and labels
  491. backgroundColor: null, // null for transparent, else color
  492. borderColor: null, // set if different from the grid color
  493. tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
  494. margin: 0, // distance from the canvas edge to the grid
  495. labelMargin: 5, // in pixels
  496. axisMargin: 8, // in pixels
  497. borderWidth: 2, // in pixels
  498. minBorderMargin: null, // in pixels, null means taken from points radius
  499. markings: null, // array of ranges or fn: axes -> array of ranges
  500. markingsColor: "#f4f4f4",
  501. markingsLineWidth: 2,
  502. // interactive stuff
  503. clickable: false,
  504. hoverable: false,
  505. autoHighlight: true, // highlight in case mouse is near
  506. mouseActiveRadius: 10 // how far the mouse can be away to activate an item
  507. },
  508. interaction: {
  509. redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
  510. },
  511. hooks: {}
  512. },
  513. surface = null, // the canvas for the plot itself
  514. overlay = null, // canvas for interactive stuff on top of plot
  515. eventHolder = null, // jQuery object that events should be bound to
  516. ctx = null, octx = null,
  517. xaxes = [], yaxes = [],
  518. plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
  519. plotWidth = 0, plotHeight = 0,
  520. hooks = {
  521. processOptions: [],
  522. processRawData: [],
  523. processDatapoints: [],
  524. processOffset: [],
  525. drawBackground: [],
  526. drawSeries: [],
  527. draw: [],
  528. bindEvents: [],
  529. drawOverlay: [],
  530. shutdown: []
  531. },
  532. plot = this;
  533. // public functions
  534. plot.setData = setData;
  535. plot.setupGrid = setupGrid;
  536. plot.draw = draw;
  537. plot.getPlaceholder = function() { return placeholder; };
  538. plot.getCanvas = function() { return surface.element; };
  539. plot.getPlotOffset = function() { return plotOffset; };
  540. plot.width = function () { return plotWidth; };
  541. plot.height = function () { return plotHeight; };
  542. plot.offset = function () {
  543. var o = eventHolder.offset();
  544. o.left += plotOffset.left;
  545. o.top += plotOffset.top;
  546. return o;
  547. };
  548. plot.getData = function () { return series; };
  549. plot.getAxes = function () {
  550. var res = {}, i;
  551. $.each(xaxes.concat(yaxes), function (_, axis) {
  552. if (axis)
  553. res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
  554. });
  555. return res;
  556. };
  557. plot.getXAxes = function () { return xaxes; };
  558. plot.getYAxes = function () { return yaxes; };
  559. plot.c2p = canvasToAxisCoords;
  560. plot.p2c = axisToCanvasCoords;
  561. plot.getOptions = function () { return options; };
  562. plot.highlight = highlight;
  563. plot.unhighlight = unhighlight;
  564. plot.triggerRedrawOverlay = triggerRedrawOverlay;
  565. plot.pointOffset = function(point) {
  566. return {
  567. left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
  568. top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
  569. };
  570. };
  571. plot.shutdown = shutdown;
  572. plot.destroy = function () {
  573. shutdown();
  574. placeholder.removeData("plot").empty();
  575. series = [];
  576. options = null;
  577. surface = null;
  578. overlay = null;
  579. eventHolder = null;
  580. ctx = null;
  581. octx = null;
  582. xaxes = [];
  583. yaxes = [];
  584. hooks = null;
  585. highlights = [];
  586. plot = null;
  587. };
  588. plot.resize = function () {
  589. var width = placeholder.width(),
  590. height = placeholder.height();
  591. surface.resize(width, height);
  592. overlay.resize(width, height);
  593. };
  594. // public attributes
  595. plot.hooks = hooks;
  596. // initialize
  597. initPlugins(plot);
  598. parseOptions(options_);
  599. setupCanvases();
  600. setData(data_);
  601. setupGrid();
  602. draw();
  603. bindEvents();
  604. function executeHooks(hook, args) {
  605. args = [plot].concat(args);
  606. for (var i = 0; i < hook.length; ++i)
  607. hook[i].apply(this, args);
  608. }
  609. function initPlugins() {
  610. // References to key classes, allowing plugins to modify them
  611. var classes = {
  612. Canvas: Canvas
  613. };
  614. for (var i = 0; i < plugins.length; ++i) {
  615. var p = plugins[i];
  616. p.init(plot, classes);
  617. if (p.options)
  618. $.extend(true, options, p.options);
  619. }
  620. }
  621. function parseOptions(opts) {
  622. $.extend(true, options, opts);
  623. // $.extend merges arrays, rather than replacing them. When less
  624. // colors are provided than the size of the default palette, we
  625. // end up with those colors plus the remaining defaults, which is
  626. // not expected behavior; avoid it by replacing them here.
  627. if (opts && opts.colors) {
  628. options.colors = opts.colors;
  629. }
  630. if (options.xaxis.color == null)
  631. options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  632. if (options.yaxis.color == null)
  633. options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  634. if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
  635. options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
  636. if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
  637. options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
  638. if (options.grid.borderColor == null)
  639. options.grid.borderColor = options.grid.color;
  640. if (options.grid.tickColor == null)
  641. options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  642. // Fill in defaults for axis options, including any unspecified
  643. // font-spec fields, if a font-spec was provided.
  644. // If no x/y axis options were provided, create one of each anyway,
  645. // since the rest of the code assumes that they exist.
  646. var i, axisOptions, axisCount,
  647. fontSize = placeholder.css("font-size"),
  648. fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
  649. fontDefaults = {
  650. style: placeholder.css("font-style"),
  651. size: Math.round(0.8 * fontSizeDefault),
  652. variant: placeholder.css("font-variant"),
  653. weight: placeholder.css("font-weight"),
  654. family: placeholder.css("font-family")
  655. };
  656. axisCount = options.xaxes.length || 1;
  657. for (i = 0; i < axisCount; ++i) {
  658. axisOptions = options.xaxes[i];
  659. if (axisOptions && !axisOptions.tickColor) {
  660. axisOptions.tickColor = axisOptions.color;
  661. }
  662. axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
  663. options.xaxes[i] = axisOptions;
  664. if (axisOptions.font) {
  665. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  666. if (!axisOptions.font.color) {
  667. axisOptions.font.color = axisOptions.color;
  668. }
  669. if (!axisOptions.font.lineHeight) {
  670. axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
  671. }
  672. }
  673. }
  674. axisCount = options.yaxes.length || 1;
  675. for (i = 0; i < axisCount; ++i) {
  676. axisOptions = options.yaxes[i];
  677. if (axisOptions && !axisOptions.tickColor) {
  678. axisOptions.tickColor = axisOptions.color;
  679. }
  680. axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
  681. options.yaxes[i] = axisOptions;
  682. if (axisOptions.font) {
  683. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  684. if (!axisOptions.font.color) {
  685. axisOptions.font.color = axisOptions.color;
  686. }
  687. if (!axisOptions.font.lineHeight) {
  688. axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
  689. }
  690. }
  691. }
  692. // backwards compatibility, to be removed in future
  693. if (options.xaxis.noTicks && options.xaxis.ticks == null)
  694. options.xaxis.ticks = options.xaxis.noTicks;
  695. if (options.yaxis.noTicks && options.yaxis.ticks == null)
  696. options.yaxis.ticks = options.yaxis.noTicks;
  697. if (options.x2axis) {
  698. options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
  699. options.xaxes[1].position = "top";
  700. // Override the inherit to allow the axis to auto-scale
  701. if (options.x2axis.min == null) {
  702. options.xaxes[1].min = null;
  703. }
  704. if (options.x2axis.max == null) {
  705. options.xaxes[1].max = null;
  706. }
  707. }
  708. if (options.y2axis) {
  709. options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
  710. options.yaxes[1].position = "right";
  711. // Override the inherit to allow the axis to auto-scale
  712. if (options.y2axis.min == null) {
  713. options.yaxes[1].min = null;
  714. }
  715. if (options.y2axis.max == null) {
  716. options.yaxes[1].max = null;
  717. }
  718. }
  719. if (options.grid.coloredAreas)
  720. options.grid.markings = options.grid.coloredAreas;
  721. if (options.grid.coloredAreasColor)
  722. options.grid.markingsColor = options.grid.coloredAreasColor;
  723. if (options.lines)
  724. $.extend(true, options.series.lines, options.lines);
  725. if (options.points)
  726. $.extend(true, options.series.points, options.points);
  727. if (options.bars)
  728. $.extend(true, options.series.bars, options.bars);
  729. if (options.shadowSize != null)
  730. options.series.shadowSize = options.shadowSize;
  731. if (options.highlightColor != null)
  732. options.series.highlightColor = options.highlightColor;
  733. // save options on axes for future reference
  734. for (i = 0; i < options.xaxes.length; ++i)
  735. getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
  736. for (i = 0; i < options.yaxes.length; ++i)
  737. getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
  738. // add hooks from options
  739. for (var n in hooks)
  740. if (options.hooks[n] && options.hooks[n].length)
  741. hooks[n] = hooks[n].concat(options.hooks[n]);
  742. executeHooks(hooks.processOptions, [options]);
  743. }
  744. function setData(d) {
  745. series = parseData(d);
  746. fillInSeriesOptions();
  747. processData();
  748. }
  749. function parseData(d) {
  750. var res = [];
  751. for (var i = 0; i < d.length; ++i) {
  752. var s = $.extend(true, {}, options.series);
  753. if (d[i].data != null) {
  754. s.data = d[i].data; // move the data instead of deep-copy
  755. delete d[i].data;
  756. $.extend(true, s, d[i]);
  757. d[i].data = s.data;
  758. }
  759. else
  760. s.data = d[i];
  761. res.push(s);
  762. }
  763. return res;
  764. }
  765. function axisNumber(obj, coord) {
  766. var a = obj[coord + "axis"];
  767. if (typeof a == "object") // if we got a real axis, extract number
  768. a = a.n;
  769. if (typeof a != "number")
  770. a = 1; // default to first axis
  771. return a;
  772. }
  773. function allAxes() {
  774. // return flat array without annoying null entries
  775. return $.grep(xaxes.concat(yaxes), function (a) { return a; });
  776. }
  777. function canvasToAxisCoords(pos) {
  778. // return an object with x/y corresponding to all used axes
  779. var res = {}, i, axis;
  780. for (i = 0; i < xaxes.length; ++i) {
  781. axis = xaxes[i];
  782. if (axis && axis.used)
  783. res["x" + axis.n] = axis.c2p(pos.left);
  784. }
  785. for (i = 0; i < yaxes.length; ++i) {
  786. axis = yaxes[i];
  787. if (axis && axis.used)
  788. res["y" + axis.n] = axis.c2p(pos.top);
  789. }
  790. if (res.x1 !== undefined)
  791. res.x = res.x1;
  792. if (res.y1 !== undefined)
  793. res.y = res.y1;
  794. return res;
  795. }
  796. function axisToCanvasCoords(pos) {
  797. // get canvas coords from the first pair of x/y found in pos
  798. var res = {}, i, axis, key;
  799. for (i = 0; i < xaxes.length; ++i) {
  800. axis = xaxes[i];
  801. if (axis && axis.used) {
  802. key = "x" + axis.n;
  803. if (pos[key] == null && axis.n == 1)
  804. key = "x";
  805. if (pos[key] != null) {
  806. res.left = axis.p2c(pos[key]);
  807. break;
  808. }
  809. }
  810. }
  811. for (i = 0; i < yaxes.length; ++i) {
  812. axis = yaxes[i];
  813. if (axis && axis.used) {
  814. key = "y" + axis.n;
  815. if (pos[key] == null && axis.n == 1)
  816. key = "y";
  817. if (pos[key] != null) {
  818. res.top = axis.p2c(pos[key]);
  819. break;
  820. }
  821. }
  822. }
  823. return res;
  824. }
  825. function getOrCreateAxis(axes, number) {
  826. if (!axes[number - 1])
  827. axes[number - 1] = {
  828. n: number, // save the number for future reference
  829. direction: axes == xaxes ? "x" : "y",
  830. options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
  831. };
  832. return axes[number - 1];
  833. }
  834. function fillInSeriesOptions() {
  835. var neededColors = series.length, maxIndex = -1, i;
  836. // Subtract the number of series that already have fixed colors or
  837. // color indexes from the number that we still need to generate.
  838. for (i = 0; i < series.length; ++i) {
  839. var sc = series[i].color;
  840. if (sc != null) {
  841. neededColors--;
  842. if (typeof sc == "number" && sc > maxIndex) {
  843. maxIndex = sc;
  844. }
  845. }
  846. }
  847. // If any of the series have fixed color indexes, then we need to
  848. // generate at least as many colors as the highest index.
  849. if (neededColors <= maxIndex) {
  850. neededColors = maxIndex + 1;
  851. }
  852. // Generate all the colors, using first the option colors and then
  853. // variations on those colors once they're exhausted.
  854. var c, colors = [], colorPool = options.colors,
  855. colorPoolSize = colorPool.length, variation = 0;
  856. for (i = 0; i < neededColors; i++) {
  857. c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
  858. // Each time we exhaust the colors in the pool we adjust
  859. // a scaling factor used to produce more variations on
  860. // those colors. The factor alternates negative/positive
  861. // to produce lighter/darker colors.
  862. // Reset the variation after every few cycles, or else
  863. // it will end up producing only white or black colors.
  864. if (i % colorPoolSize == 0 && i) {
  865. if (variation >= 0) {
  866. if (variation < 0.5) {
  867. variation = -variation - 0.2;
  868. } else variation = 0;
  869. } else variation = -variation;
  870. }
  871. colors[i] = c.scale('rgb', 1 + variation);
  872. }
  873. // Finalize the series options, filling in their colors
  874. var colori = 0, s;
  875. for (i = 0; i < series.length; ++i) {
  876. s = series[i];
  877. // assign colors
  878. if (s.color == null) {
  879. s.color = colors[colori].toString();
  880. ++colori;
  881. }
  882. else if (typeof s.color == "number")
  883. s.color = colors[s.color].toString();
  884. // turn on lines automatically in case nothing is set
  885. if (s.lines.show == null) {
  886. var v, show = true;
  887. for (v in s)
  888. if (s[v] && s[v].show) {
  889. show = false;
  890. break;
  891. }
  892. if (show)
  893. s.lines.show = true;
  894. }
  895. // If nothing was provided for lines.zero, default it to match
  896. // lines.fill, since areas by default should extend to zero.
  897. if (s.lines.zero == null) {
  898. s.lines.zero = !!s.lines.fill;
  899. }
  900. // setup axes
  901. s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
  902. s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
  903. }
  904. }
  905. function processData() {
  906. var topSentry = Number.POSITIVE_INFINITY,
  907. bottomSentry = Number.NEGATIVE_INFINITY,
  908. fakeInfinity = Number.MAX_VALUE,
  909. i, j, k, m, length,
  910. s, points, ps, x, y, axis, val, f, p,
  911. data, format;
  912. function updateAxis(axis, min, max) {
  913. if (min < axis.datamin && min != -fakeInfinity)
  914. axis.datamin = min;
  915. if (max > axis.datamax && max != fakeInfinity)
  916. axis.datamax = max;
  917. }
  918. $.each(allAxes(), function (_, axis) {
  919. // init axis
  920. axis.datamin = topSentry;
  921. axis.datamax = bottomSentry;
  922. axis.used = false;
  923. });
  924. for (i = 0; i < series.length; ++i) {
  925. s = series[i];
  926. s.datapoints = { points: [] };
  927. executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
  928. }
  929. // first pass: clean and copy data
  930. for (i = 0; i < series.length; ++i) {
  931. s = series[i];
  932. data = s.data;
  933. format = s.datapoints.format;
  934. if (!format) {
  935. format = [];
  936. // find out how to copy
  937. format.push({ x: true, number: true, required: true });
  938. format.push({ y: true, number: true, required: true });
  939. if (s.bars.show || (s.lines.show && s.lines.fill)) {
  940. var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
  941. format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
  942. if (s.bars.horizontal) {
  943. delete format[format.length - 1].y;
  944. format[format.length - 1].x = true;
  945. }
  946. }
  947. s.datapoints.format = format;
  948. }
  949. if (s.datapoints.pointsize != null)
  950. continue; // already filled in
  951. s.datapoints.pointsize = format.length;
  952. ps = s.datapoints.pointsize;
  953. points = s.datapoints.points;
  954. var insertSteps = s.lines.show && s.lines.steps;
  955. s.xaxis.used = s.yaxis.used = true;
  956. for (j = k = 0; j < data.length; ++j, k += ps) {
  957. p = data[j];
  958. var nullify = p == null;
  959. if (!nullify) {
  960. for (m = 0; m < ps; ++m) {
  961. val = p[m];
  962. f = format[m];
  963. if (f) {
  964. if (f.number && val != null) {
  965. val = +val; // convert to number
  966. if (isNaN(val))
  967. val = null;
  968. else if (val == Infinity)
  969. val = fakeInfinity;
  970. else if (val == -Infinity)
  971. val = -fakeInfinity;
  972. }
  973. if (val == null) {
  974. if (f.required)
  975. nullify = true;
  976. if (f.defaultValue != null)
  977. val = f.defaultValue;
  978. }
  979. }
  980. points[k + m] = val;
  981. }
  982. }
  983. if (nullify) {
  984. for (m = 0; m < ps; ++m) {
  985. val = points[k + m];
  986. if (val != null) {
  987. f = format[m];
  988. // extract min/max info
  989. if (f.autoscale !== false) {
  990. if (f.x) {
  991. updateAxis(s.xaxis, val, val);
  992. }
  993. if (f.y) {
  994. updateAxis(s.yaxis, val, val);
  995. }
  996. }
  997. }
  998. points[k + m] = null;
  999. }
  1000. }
  1001. else {
  1002. // a little bit of line specific stuff that
  1003. // perhaps shouldn't be here, but lacking
  1004. // better means...
  1005. if (insertSteps && k > 0
  1006. && points[k - ps] != null
  1007. && points[k - ps] != points[k]
  1008. && points[k - ps + 1] != points[k + 1]) {
  1009. // copy the point to make room for a middle point
  1010. for (m = 0; m < ps; ++m)
  1011. points[k + ps + m] = points[k + m];
  1012. // middle point has same y
  1013. points[k + 1] = points[k - ps + 1];
  1014. // we've added a point, better reflect that
  1015. k += ps;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. // give the hooks a chance to run
  1021. for (i = 0; i < series.length; ++i) {
  1022. s = series[i];
  1023. executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
  1024. }
  1025. // second pass: find datamax/datamin for auto-scaling
  1026. for (i = 0; i < series.length; ++i) {
  1027. s = series[i];
  1028. points = s.datapoints.points;
  1029. ps = s.datapoints.pointsize;
  1030. format = s.datapoints.format;
  1031. var xmin = topSentry, ymin = topSentry,
  1032. xmax = bottomSentry, ymax = bottomSentry;
  1033. for (j = 0; j < points.length; j += ps) {
  1034. if (points[j] == null)
  1035. continue;
  1036. for (m = 0; m < ps; ++m) {
  1037. val = points[j + m];
  1038. f = format[m];
  1039. if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
  1040. continue;
  1041. if (f.x) {
  1042. if (val < xmin)
  1043. xmin = val;
  1044. if (val > xmax)
  1045. xmax = val;
  1046. }
  1047. if (f.y) {
  1048. if (val < ymin)
  1049. ymin = val;
  1050. if (val > ymax)
  1051. ymax = val;
  1052. }
  1053. }
  1054. }
  1055. if (s.bars.show) {
  1056. // make sure we got room for the bar on the dancing floor
  1057. var delta;
  1058. switch (s.bars.align) {
  1059. case "left":
  1060. delta = 0;
  1061. break;
  1062. case "right":
  1063. delta = -s.bars.barWidth;
  1064. break;
  1065. default:
  1066. delta = -s.bars.barWidth / 2;
  1067. }
  1068. if (s.bars.horizontal) {
  1069. ymin += delta;
  1070. ymax += delta + s.bars.barWidth;
  1071. }
  1072. else {
  1073. xmin += delta;
  1074. xmax += delta + s.bars.barWidth;
  1075. }
  1076. }
  1077. updateAxis(s.xaxis, xmin, xmax);
  1078. updateAxis(s.yaxis, ymin, ymax);
  1079. }
  1080. $.each(allAxes(), function (_, axis) {
  1081. if (axis.datamin == topSentry)
  1082. axis.datamin = null;
  1083. if (axis.datamax == bottomSentry)
  1084. axis.datamax = null;
  1085. });
  1086. }
  1087. function setupCanvases() {
  1088. // Make sure the placeholder is clear of everything except canvases
  1089. // from a previous plot in this container that we'll try to re-use.
  1090. placeholder.css("padding", 0) // padding messes up the positioning
  1091. .children().filter(function(){
  1092. return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base');
  1093. }).remove();
  1094. if (placeholder.css("position") == 'static')
  1095. placeholder.css("position", "relative"); // for positioning labels and overlay
  1096. surface = new Canvas("flot-base", placeholder);
  1097. overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features
  1098. ctx = surface.context;
  1099. octx = overlay.context;
  1100. // define which element we're listening for events on
  1101. eventHolder = $(overlay.element).unbind();
  1102. // If we're re-using a plot object, shut down the old one
  1103. var existing = placeholder.data("plot");
  1104. if (existing) {
  1105. existing.shutdown();
  1106. overlay.clear();
  1107. }
  1108. // save in case we get replotted
  1109. placeholder.data("plot", plot);
  1110. }
  1111. function bindEvents() {
  1112. // bind events
  1113. if (options.grid.hoverable) {
  1114. eventHolder.mousemove(onMouseMove);
  1115. // Use bind, rather than .mouseleave, because we officially
  1116. // still support jQuery 1.2.6, which doesn't define a shortcut
  1117. // for mouseenter or mouseleave. This was a bug/oversight that
  1118. // was fixed somewhere around 1.3.x. We can return to using
  1119. // .mouseleave when we drop support for 1.2.6.
  1120. eventHolder.bind("mouseleave", onMouseLeave);
  1121. }
  1122. if (options.grid.clickable)
  1123. eventHolder.click(onClick);
  1124. executeHooks(hooks.bindEvents, [eventHolder]);
  1125. }
  1126. function shutdown() {
  1127. if (redrawTimeout)
  1128. clearTimeout(redrawTimeout);
  1129. eventHolder.unbind("mousemove", onMouseMove);
  1130. eventHolder.unbind("mouseleave", onMouseLeave);
  1131. eventHolder.unbind("click", onClick);
  1132. executeHooks(hooks.shutdown, [eventHolder]);
  1133. }
  1134. function setTransformationHelpers(axis) {
  1135. // set helper functions on the axis, assumes plot area
  1136. // has been computed already
  1137. function identity(x) { return x; }
  1138. var s, m, t = axis.options.transform || identity,
  1139. it = axis.options.inverseTransform;
  1140. // precompute how much the axis is scaling a point
  1141. // in canvas space
  1142. if (axis.direction == "x") {
  1143. s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
  1144. m = Math.min(t(axis.max), t(axis.min));
  1145. }
  1146. else {
  1147. s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
  1148. s = -s;
  1149. m = Math.max(t(axis.max), t(axis.min));
  1150. }
  1151. // data point to canvas coordinate
  1152. if (t == identity) // slight optimization
  1153. axis.p2c = function (p) { return (p - m) * s; };
  1154. else
  1155. axis.p2c = function (p) { return (t(p) - m) * s; };
  1156. // canvas coordinate to data point
  1157. if (!it)
  1158. axis.c2p = function (c) { return m + c / s; };
  1159. else
  1160. axis.c2p = function (c) { return it(m + c / s); };
  1161. }
  1162. function measureTickLabels(axis) {
  1163. var opts = axis.options,
  1164. ticks = axis.ticks || [],
  1165. labelWidth = opts.labelWidth || 0,
  1166. labelHeight = opts.labelHeight || 0,
  1167. maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null),
  1168. legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
  1169. layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
  1170. font = opts.font || "flot-tick-label tickLabel";
  1171. for (var i = 0; i < ticks.length; ++i) {
  1172. var t = ticks[i];
  1173. if (!t.label)
  1174. continue;
  1175. var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
  1176. labelWidth = Math.max(labelWidth, info.width);
  1177. labelHeight = Math.max(labelHeight, info.height);
  1178. }
  1179. axis.labelWidth = opts.labelWidth || labelWidth;
  1180. axis.labelHeight = opts.labelHeight || labelHeight;
  1181. }
  1182. function allocateAxisBoxFirstPhase(axis) {
  1183. // find the bounding box of the axis by looking at label
  1184. // widths/heights and ticks, make room by diminishing the
  1185. // plotOffset; this first phase only looks at one
  1186. // dimension per axis, the other dimension depends on the
  1187. // other axes so will have to wait
  1188. var lw = axis.labelWidth,
  1189. lh = axis.labelHeight,
  1190. pos = axis.options.position,
  1191. isXAxis = axis.direction === "x",
  1192. tickLength = axis.options.tickLength,
  1193. axisMargin = options.grid.axisMargin,
  1194. padding = options.grid.labelMargin,
  1195. innermost = true,
  1196. outermost = true,
  1197. first = true,
  1198. found = false;
  1199. // Determine the axis's position in its direction and on its side
  1200. $.each(isXAxis ? xaxes : yaxes, function(i, a) {
  1201. if (a && (a.show || a.reserveSpace)) {
  1202. if (a === axis) {
  1203. found = true;
  1204. } else if (a.options.position === pos) {
  1205. if (found) {
  1206. outermost = false;
  1207. } else {
  1208. innermost = false;
  1209. }
  1210. }
  1211. if (!found) {
  1212. first = false;
  1213. }
  1214. }
  1215. });
  1216. // The outermost axis on each side has no margin
  1217. if (outermost) {
  1218. axisMargin = 0;
  1219. }
  1220. // The ticks for the first axis in each direction stretch across
  1221. if (tickLength == null) {
  1222. tickLength = first ? "full" : 5;
  1223. }
  1224. if (!isNaN(+tickLength))
  1225. padding += +tickLength;
  1226. if (isXAxis) {
  1227. lh += padding;
  1228. if (pos == "bottom") {
  1229. plotOffset.bottom += lh + axisMargin;
  1230. axis.box = { top: surface.height - plotOffset.bottom, height: lh };
  1231. }
  1232. else {
  1233. axis.box = { top: plotOffset.top + axisMargin, height: lh };
  1234. plotOffset.top += lh + axisMargin;
  1235. }
  1236. }
  1237. else {
  1238. lw += padding;
  1239. if (pos == "left") {
  1240. axis.box = { left: plotOffset.left + axisMargin, width: lw };
  1241. plotOffset.left += lw + axisMargin;
  1242. }
  1243. else {
  1244. plotOffset.right += lw + axisMargin;
  1245. axis.box = { left: surface.width - plotOffset.right, width: lw };
  1246. }
  1247. }
  1248. // save for future reference
  1249. axis.position = pos;
  1250. axis.tickLength = tickLength;
  1251. axis.box.padding = padding;
  1252. axis.innermost = innermost;
  1253. }
  1254. function allocateAxisBoxSecondPhase(axis) {
  1255. // now that all axis boxes have been placed in one
  1256. // dimension, we can set the remaining dimension coordinates
  1257. if (axis.direction == "x") {
  1258. axis.box.left = plotOffset.left - axis.labelWidth / 2;
  1259. axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
  1260. }
  1261. else {
  1262. axis.box.top = plotOffset.top - axis.labelHeight / 2;
  1263. axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
  1264. }
  1265. }
  1266. function adjustLayoutForThingsStickingOut() {
  1267. // possibly adjust plot offset to ensure everything stays
  1268. // inside the canvas and isn't clipped off
  1269. var minMargin = options.grid.minBorderMargin,
  1270. axis, i;
  1271. // check stuff from the plot (FIXME: this should just read
  1272. // a value from the series, otherwise it's impossible to
  1273. // customize)
  1274. if (minMargin == null) {
  1275. minMargin = 0;
  1276. for (i = 0; i < series.length; ++i)
  1277. minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
  1278. }
  1279. var margins = {
  1280. left: minMargin,
  1281. right: minMargin,
  1282. top: minMargin,
  1283. bottom: minMargin
  1284. };
  1285. // check axis labels, note we don't check the actual
  1286. // labels but instead use the overall width/height to not
  1287. // jump as much around with replots
  1288. $.each(allAxes(), function (_, axis) {
  1289. if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
  1290. if (axis.direction === "x") {
  1291. margins.left = Math.max(margins.left, axis.labelWidth / 2);
  1292. margins.right = Math.max(margins.right, axis.labelWidth / 2);
  1293. } else {
  1294. margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
  1295. margins.top = Math.max(margins.top, axis.labelHeight / 2);
  1296. }
  1297. }
  1298. });
  1299. plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
  1300. plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
  1301. plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
  1302. plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
  1303. }
  1304. function setupGrid() {
  1305. var i, axes = allAxes(), showGrid = options.grid.show;
  1306. // Initialize the plot's offset from the edge of the canvas
  1307. for (var a in plotOffset) {
  1308. var margin = options.grid.margin || 0;
  1309. plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
  1310. }
  1311. executeHooks(hooks.processOffset, [plotOffset]);
  1312. // If the grid is visible, add its border width to the offset
  1313. for (var a in plotOffset) {
  1314. if(typeof(options.grid.borderWidth) == "object") {
  1315. plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
  1316. }
  1317. else {
  1318. plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
  1319. }
  1320. }
  1321. $.each(axes, function (_, axis) {
  1322. var axisOpts = axis.options;
  1323. axis.show = axisOpts.show == null ? axis.used : axisOpts.show;
  1324. axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace;
  1325. setRange(axis);
  1326. });
  1327. if (showGrid) {
  1328. var allocatedAxes = $.grep(axes, function (axis) {
  1329. return axis.show || axis.reserveSpace;
  1330. });
  1331. $.each(allocatedAxes, function (_, axis) {
  1332. // make the ticks
  1333. setupTickGeneration(axis);
  1334. setTicks(axis);
  1335. snapRangeToTicks(axis, axis.ticks);
  1336. // find labelWidth/Height for axis
  1337. measureTickLabels(axis);
  1338. });
  1339. // with all dimensions calculated, we can compute the
  1340. // axis bounding boxes, start from the outside
  1341. // (reverse order)
  1342. for (i = allocatedAxes.length - 1; i >= 0; --i)
  1343. allocateAxisBoxFirstPhase(allocatedAxes[i]);
  1344. // make sure we've got enough space for things that
  1345. // might stick out
  1346. adjustLayoutForThingsStickingOut();
  1347. $.each(allocatedAxes, function (_, axis) {
  1348. allocateAxisBoxSecondPhase(axis);
  1349. });
  1350. }
  1351. plotWidth = surface.width - plotOffset.left - plotOffset.right;
  1352. plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
  1353. // now we got the proper plot dimensions, we can compute the scaling
  1354. $.each(axes, function (_, axis) {
  1355. setTransformationHelpers(axis);
  1356. });
  1357. if (showGrid) {
  1358. drawAxisLabels();
  1359. }
  1360. insertLegend();
  1361. }
  1362. function setRange(axis) {
  1363. var opts = axis.options,
  1364. min = +(opts.min != null ? opts.min : axis.datamin),
  1365. max = +(opts.max != null ? opts.max : axis.datamax),
  1366. delta = max - min;
  1367. if (delta == 0.0) {
  1368. // degenerate case
  1369. var widen = max == 0 ? 1 : 0.01;
  1370. if (opts.min == null)
  1371. min -= widen;
  1372. // always widen max if we couldn't widen min to ensure we
  1373. // don't fall into min == max which doesn't work
  1374. if (opts.max == null || opts.min != null)
  1375. max += widen;
  1376. }
  1377. else {
  1378. // consider autoscaling
  1379. var margin = opts.autoscaleMargin;
  1380. if (margin != null) {
  1381. if (opts.min == null) {
  1382. min -= delta * margin;
  1383. // make sure we don't go below zero if all values
  1384. // are positive
  1385. if (min < 0 && axis.datamin != null && axis.datamin >= 0)
  1386. min = 0;
  1387. }
  1388. if (opts.max == null) {
  1389. max += delta * margin;
  1390. if (max > 0 && axis.datamax != null && axis.datamax <= 0)
  1391. max = 0;
  1392. }
  1393. }
  1394. }
  1395. axis.min = min;
  1396. axis.max = max;
  1397. }
  1398. function setupTickGeneration(axis) {
  1399. var opts = axis.options;
  1400. // estimate number of ticks
  1401. var noTicks;
  1402. if (typeof opts.ticks == "number" && opts.ticks > 0)
  1403. noTicks = opts.ticks;
  1404. else
  1405. // heuristic based on the model a*sqrt(x) fitted to
  1406. // some data points that seemed reasonable
  1407. noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
  1408. var delta = (axis.max - axis.min) / noTicks,
  1409. dec = -Math.floor(Math.log(delta) / Math.LN10),
  1410. maxDec = opts.tickDecimals;
  1411. if (maxDec != null && dec > maxDec) {
  1412. dec = maxDec;
  1413. }
  1414. var magn = Math.pow(10, -dec),
  1415. norm = delta / magn, // norm is between 1.0 and 10.0
  1416. size;
  1417. if (norm < 1.5) {
  1418. size = 1;
  1419. } else if (norm < 3) {
  1420. size = 2;
  1421. // special case for 2.5, requires an extra decimal
  1422. if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
  1423. size = 2.5;
  1424. ++dec;
  1425. }
  1426. } else if (norm < 7.5) {
  1427. size = 5;
  1428. } else {
  1429. size = 10;
  1430. }
  1431. size *= magn;
  1432. if (opts.minTickSize != null && size < opts.minTickSize) {
  1433. size = opts.minTickSize;
  1434. }
  1435. axis.delta = delta;
  1436. axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
  1437. axis.tickSize = opts.tickSize || size;
  1438. // Time mode was moved to a plug-in in 0.8, and since so many people use it
  1439. // we'll add an especially friendly reminder to make sure they included it.
  1440. if (opts.mode == "time" && !axis.tickGenerator) {
  1441. throw new Error("Time mode requires the flot.time plugin.");
  1442. }
  1443. // Flot supports base-10 axes; any other mode else is handled by a plug-in,
  1444. // like flot.time.js.
  1445. if (!axis.tickGenerator) {
  1446. axis.tickGenerator = function (axis) {
  1447. var ticks = [],
  1448. start = floorInBase(axis.min, axis.tickSize),
  1449. i = 0,
  1450. v = Number.NaN,
  1451. prev;
  1452. do {
  1453. prev = v;
  1454. v = start + i * axis.tickSize;
  1455. ticks.push(v);
  1456. ++i;
  1457. } while (v < axis.max && v != prev);
  1458. return ticks;
  1459. };
  1460. axis.tickFormatter = function (value, axis) {
  1461. var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
  1462. var formatted = "" + Math.round(value * factor) / factor;
  1463. // If tickDecimals was specified, ensure that we have exactly that
  1464. // much precision; otherwise default to the value's own precision.
  1465. if (axis.tickDecimals != null) {
  1466. var decimal = formatted.indexOf(".");
  1467. var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
  1468. if (precision < axis.tickDecimals) {
  1469. return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
  1470. }
  1471. }
  1472. return formatted;
  1473. };
  1474. }
  1475. if ($.isFunction(opts.tickFormatter))
  1476. axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
  1477. if (opts.alignTicksWithAxis != null) {
  1478. var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
  1479. if (otherAxis && otherAxis.used && otherAxis != axis) {
  1480. // consider snapping min/max to outermost nice ticks
  1481. var niceTicks = axis.tickGenerator(axis);
  1482. if (niceTicks.length > 0) {
  1483. if (opts.min == null)
  1484. axis.min = Math.min(axis.min, niceTicks[0]);
  1485. if (opts.max == null && niceTicks.length > 1)
  1486. axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
  1487. }
  1488. axis.tickGenerator = function (axis) {
  1489. // copy ticks, scaled to this axis
  1490. var ticks = [], v, i;
  1491. for (i = 0; i < otherAxis.ticks.length; ++i) {
  1492. v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
  1493. v = axis.min + v * (axis.max - axis.min);
  1494. ticks.push(v);
  1495. }
  1496. return ticks;
  1497. };
  1498. // we might need an extra decimal since forced
  1499. // ticks don't necessarily fit naturally
  1500. if (!axis.mode && opts.tickDecimals == null) {
  1501. var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
  1502. ts = axis.tickGenerator(axis);
  1503. // only proceed if the tick interval rounded
  1504. // with an extra decimal doesn't give us a
  1505. // zero at end
  1506. if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
  1507. axis.tickDecimals = extraDec;
  1508. }
  1509. }
  1510. }
  1511. }
  1512. function setTicks(axis) {
  1513. var oticks = axis.options.ticks, ticks = [];
  1514. if (oticks == null || (typeof oticks == "number" && oticks > 0))
  1515. ticks = axis.tickGenerator(axis);
  1516. else if (oticks) {
  1517. if ($.isFunction(oticks))
  1518. // generate the ticks
  1519. ticks = oticks(axis);
  1520. else
  1521. ticks = oticks;
  1522. }
  1523. // clean up/labelify the supplied ticks, copy them over
  1524. var i, v;
  1525. axis.ticks = [];
  1526. for (i = 0; i < ticks.length; ++i) {
  1527. var label = null;
  1528. var t = ticks[i];
  1529. if (typeof t == "object") {
  1530. v = +t[0];
  1531. if (t.length > 1)
  1532. label = t[1];
  1533. }
  1534. else
  1535. v = +t;
  1536. if (label == null)
  1537. label = axis.tickFormatter(v, axis);
  1538. if (!isNaN(v))
  1539. axis.ticks.push({ v: v, label: label });
  1540. }
  1541. }
  1542. function snapRangeToTicks(axis, ticks) {
  1543. if (axis.options.autoscaleMargin && ticks.length > 0) {
  1544. // snap to ticks
  1545. if (axis.options.min == null)
  1546. axis.min = Math.min(axis.min, ticks[0].v);
  1547. if (axis.options.max == null && ticks.length > 1)
  1548. axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
  1549. }
  1550. }
  1551. function draw() {
  1552. surface.clear();
  1553. executeHooks(hooks.drawBackground, [ctx]);
  1554. var grid = options.grid;
  1555. // draw background, if any
  1556. if (grid.show && grid.backgroundColor)
  1557. drawBackground();
  1558. if (grid.show && !grid.aboveData) {
  1559. drawGrid();
  1560. }
  1561. for (var i = 0; i < series.length; ++i) {
  1562. executeHooks(hooks.drawSeries, [ctx, series[i]]);
  1563. drawSeries(series[i]);
  1564. }
  1565. executeHooks(hooks.draw, [ctx]);
  1566. if (grid.show && grid.aboveData) {
  1567. drawGrid();
  1568. }
  1569. surface.render();
  1570. // A draw implies that either the axes or data have changed, so we
  1571. // should probably update the overlay highlights as well.
  1572. triggerRedrawOverlay();
  1573. }
  1574. function extractRange(ranges, coord) {
  1575. var axis, from, to, key, axes = allAxes();
  1576. for (var i = 0; i < axes.length; ++i) {
  1577. axis = axes[i];
  1578. if (axis.direction == coord) {
  1579. key = coord + axis.n + "axis";
  1580. if (!ranges[key] && axis.n == 1)
  1581. key = coord + "axis"; // support x1axis as xaxis
  1582. if (ranges[key]) {
  1583. from = ranges[key].from;
  1584. to = ranges[key].to;
  1585. break;
  1586. }
  1587. }
  1588. }
  1589. // backwards-compat stuff - to be removed in future
  1590. if (!ranges[key]) {
  1591. axis = coord == "x" ? xaxes[0] : yaxes[0];
  1592. from = ranges[coord + "1"];
  1593. to = ranges[coord + "2"];
  1594. }
  1595. // auto-reverse as an added bonus
  1596. if (from != null && to != null && from > to) {
  1597. var tmp = from;
  1598. from = to;
  1599. to = tmp;
  1600. }
  1601. return { from: from, to: to, axis: axis };
  1602. }
  1603. function drawBackground() {
  1604. ctx.save();
  1605. ctx.translate(plotOffset.left, plotOffset.top);
  1606. ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
  1607. ctx.fillRect(0, 0, plotWidth, plotHeight);
  1608. ctx.restore();
  1609. }
  1610. function drawGrid() {
  1611. var i, axes, bw, bc;
  1612. ctx.save();
  1613. ctx.translate(plotOffset.left, plotOffset.top);
  1614. // draw markings
  1615. var markings = options.grid.markings;
  1616. if (markings) {
  1617. if ($.isFunction(markings)) {
  1618. axes = plot.getAxes();
  1619. // xmin etc. is backwards compatibility, to be
  1620. // removed in the future
  1621. axes.xmin = axes.xaxis.min;
  1622. axes.xmax = axes.xaxis.max;
  1623. axes.ymin = axes.yaxis.min;
  1624. axes.ymax = axes.yaxis.max;
  1625. markings = markings(axes);
  1626. }
  1627. for (i = 0; i < markings.length; ++i) {
  1628. var m = markings[i],
  1629. xrange = extractRange(m, "x"),
  1630. yrange = extractRange(m, "y");
  1631. // fill in missing
  1632. if (xrange.from == null)
  1633. xrange.from = xrange.axis.min;
  1634. if (xrange.to == null)
  1635. xrange.to = xrange.axis.max;
  1636. if (yrange.from == null)
  1637. yrange.from = yrange.axis.min;
  1638. if (yrange.to == null)
  1639. yrange.to = yrange.axis.max;
  1640. // clip
  1641. if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
  1642. yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
  1643. continue;
  1644. xrange.from = Math.max(xrange.from, xrange.axis.min);
  1645. xrange.to = Math.min(xrange.to, xrange.axis.max);
  1646. yrange.from = Math.max(yrange.from, yrange.axis.min);
  1647. yrange.to = Math.min(yrange.to, yrange.axis.max);
  1648. var xequal = xrange.from === xrange.to,
  1649. yequal = yrange.from === yrange.to;
  1650. if (xequal && yequal) {
  1651. continue;
  1652. }
  1653. // then draw
  1654. xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
  1655. xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
  1656. yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
  1657. yrange.to = Math.floor(yrange.axis.p2c(yrange.to));
  1658. if (xequal || yequal) {
  1659. var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
  1660. subPixel = lineWidth % 2 ? 0.5 : 0;
  1661. ctx.beginPath();
  1662. ctx.strokeStyle = m.color || options.grid.markingsColor;
  1663. ctx.lineWidth = lineWidth;
  1664. if (xequal) {
  1665. ctx.moveTo(xrange.to + subPixel, yrange.from);
  1666. ctx.lineTo(xrange.to + subPixel, yrange.to);
  1667. } else {
  1668. ctx.moveTo(xrange.from, yrange.to + subPixel);
  1669. ctx.lineTo(xrange.to, yrange.to + subPixel);
  1670. }
  1671. ctx.stroke();
  1672. } else {
  1673. ctx.fillStyle = m.color || options.grid.markingsColor;
  1674. ctx.fillRect(xrange.from, yrange.to,
  1675. xrange.to - xrange.from,
  1676. yrange.from - yrange.to);
  1677. }
  1678. }
  1679. }
  1680. // draw the ticks
  1681. axes = allAxes();
  1682. bw = options.grid.borderWidth;
  1683. for (var j = 0; j < axes.length; ++j) {
  1684. var axis = axes[j], box = axis.box,
  1685. t = axis.tickLength, x, y, xoff, yoff;
  1686. if (!axis.show || axis.ticks.length == 0)
  1687. continue;
  1688. ctx.lineWidth = 1;
  1689. // find the edges
  1690. if (axis.direction == "x") {
  1691. x = 0;
  1692. if (t == "full")
  1693. y = (axis.position == "top" ? 0 : plotHeight);
  1694. else
  1695. y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
  1696. }
  1697. else {
  1698. y = 0;
  1699. if (t == "full")
  1700. x = (axis.position == "left" ? 0 : plotWidth);
  1701. else
  1702. x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
  1703. }
  1704. // draw tick bar
  1705. if (!axis.innermost) {
  1706. ctx.strokeStyle = axis.options.color;
  1707. ctx.beginPath();
  1708. xoff = yoff = 0;
  1709. if (axis.direction == "x")
  1710. xoff = plotWidth + 1;
  1711. else
  1712. yoff = plotHeight + 1;
  1713. if (ctx.lineWidth == 1) {
  1714. if (axis.direction == "x") {
  1715. y = Math.floor(y) + 0.5;
  1716. } else {
  1717. x = Math.floor(x) + 0.5;
  1718. }
  1719. }
  1720. ctx.moveTo(x, y);
  1721. ctx.lineTo(x + xoff, y + yoff);
  1722. ctx.stroke();
  1723. }
  1724. // draw ticks
  1725. ctx.strokeStyle = axis.options.tickColor;
  1726. ctx.beginPath();
  1727. for (i = 0; i < axis.ticks.length; ++i) {
  1728. var v = axis.ticks[i].v;
  1729. xoff = yoff = 0;
  1730. if (isNaN(v) || v < axis.min || v > axis.max
  1731. // skip those lying on the axes if we got a border
  1732. || (t == "full"
  1733. && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
  1734. && (v == axis.min || v == axis.max)))
  1735. continue;
  1736. if (axis.direction == "x") {
  1737. x = axis.p2c(v);
  1738. yoff = t == "full" ? -plotHeight : t;
  1739. if (axis.position == "top")
  1740. yoff = -yoff;
  1741. }
  1742. else {
  1743. y = axis.p2c(v);
  1744. xoff = t == "full" ? -plotWidth : t;
  1745. if (axis.position == "left")
  1746. xoff = -xoff;
  1747. }
  1748. if (ctx.lineWidth == 1) {
  1749. if (axis.direction == "x")
  1750. x = Math.floor(x) + 0.5;
  1751. else
  1752. y = Math.floor(y) + 0.5;
  1753. }
  1754. ctx.moveTo(x, y);
  1755. ctx.lineTo(x + xoff, y + yoff);
  1756. }
  1757. ctx.stroke();
  1758. }
  1759. // draw border
  1760. if (bw) {
  1761. // If either borderWidth or borderColor is an object, then draw the border
  1762. // line by line instead of as one rectangle
  1763. bc = options.grid.borderColor;
  1764. if(typeof bw == "object" || typeof bc == "object") {
  1765. if (typeof bw !== "object") {
  1766. bw = {top: bw, right: bw, bottom: bw, left: bw};
  1767. }
  1768. if (typeof bc !== "object") {
  1769. bc = {top: bc, right: bc, bottom: bc, left: bc};
  1770. }
  1771. if (bw.top > 0) {
  1772. ctx.strokeStyle = bc.top;
  1773. ctx.lineWidth = bw.top;
  1774. ctx.beginPath();
  1775. ctx.moveTo(0 - bw.left, 0 - bw.top/2);
  1776. ctx.lineTo(plotWidth, 0 - bw.top/2);
  1777. ctx.stroke();
  1778. }
  1779. if (bw.right > 0) {
  1780. ctx.strokeStyle = bc.right;
  1781. ctx.lineWidth = bw.right;
  1782. ctx.beginPath();
  1783. ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
  1784. ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
  1785. ctx.stroke();
  1786. }
  1787. if (bw.bottom > 0) {
  1788. ctx.strokeStyle = bc.bottom;
  1789. ctx.lineWidth = bw.bottom;
  1790. ctx.beginPath();
  1791. ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
  1792. ctx.lineTo(0, plotHeight + bw.bottom / 2);
  1793. ctx.stroke();
  1794. }
  1795. if (bw.left > 0) {
  1796. ctx.strokeStyle = bc.left;
  1797. ctx.lineWidth = bw.left;
  1798. ctx.beginPath();
  1799. ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
  1800. ctx.lineTo(0- bw.left/2, 0);
  1801. ctx.stroke();
  1802. }
  1803. }
  1804. else {
  1805. ctx.lineWidth = bw;
  1806. ctx.strokeStyle = options.grid.borderColor;
  1807. ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
  1808. }
  1809. }
  1810. ctx.restore();
  1811. }
  1812. function drawAxisLabels() {
  1813. $.each(allAxes(), function (_, axis) {
  1814. var box = axis.box,
  1815. legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
  1816. layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
  1817. font = axis.options.font || "flot-tick-label tickLabel",
  1818. tick, x, y, halign, valign;
  1819. // Remove text before checking for axis.show and ticks.length;
  1820. // otherwise plugins, like flot-tickrotor, that draw their own
  1821. // tick labels will end up with both theirs and the defaults.
  1822. surface.removeText(layer);
  1823. if (!axis.show || axis.ticks.length == 0)
  1824. return;
  1825. for (var i = 0; i < axis.ticks.length; ++i) {
  1826. tick = axis.ticks[i];
  1827. if (!tick.label || tick.v < axis.min || tick.v > axis.max)
  1828. continue;
  1829. if (axis.direction == "x") {
  1830. halign = "center";
  1831. x = plotOffset.left + axis.p2c(tick.v);
  1832. if (axis.position == "bottom") {
  1833. y = box.top + box.padding;
  1834. } else {
  1835. y = box.top + box.height - box.padding;
  1836. valign = "bottom";
  1837. }
  1838. } else {
  1839. valign = "middle";
  1840. y = plotOffset.top + axis.p2c(tick.v);
  1841. if (axis.position == "left") {
  1842. x = box.left + box.width - box.padding;
  1843. halign = "right";
  1844. } else {
  1845. x = box.left + box.padding;
  1846. }
  1847. }
  1848. surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
  1849. }
  1850. });
  1851. }
  1852. function drawSeries(series) {
  1853. if (series.lines.show)
  1854. drawSeriesLines(series);
  1855. if (series.bars.show)
  1856. drawSeriesBars(series);
  1857. if (series.points.show)
  1858. drawSeriesPoints(series);
  1859. }
  1860. function drawSeriesLines(series) {
  1861. function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
  1862. var points = datapoints.points,
  1863. ps = datapoints.pointsize,
  1864. prevx = null, prevy = null;
  1865. ctx.beginPath();
  1866. for (var i = ps; i < points.length; i += ps) {
  1867. var x1 = points[i - ps], y1 = points[i - ps + 1],
  1868. x2 = points[i], y2 = points[i + 1];
  1869. if (x1 == null || x2 == null)
  1870. continue;
  1871. // clip with ymin
  1872. if (y1 <= y2 && y1 < axisy.min) {
  1873. if (y2 < axisy.min)
  1874. continue; // line segment is outside
  1875. // compute new intersection point
  1876. x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  1877. y1 = axisy.min;
  1878. }
  1879. else if (y2 <= y1 && y2 < axisy.min) {
  1880. if (y1 < axisy.min)
  1881. continue;
  1882. x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  1883. y2 = axisy.min;
  1884. }
  1885. // clip with ymax
  1886. if (y1 >= y2 && y1 > axisy.max) {
  1887. if (y2 > axisy.max)
  1888. continue;
  1889. x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  1890. y1 = axisy.max;
  1891. }
  1892. else if (y2 >= y1 && y2 > axisy.max) {
  1893. if (y1 > axisy.max)
  1894. continue;
  1895. x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  1896. y2 = axisy.max;
  1897. }
  1898. // clip with xmin
  1899. if (x1 <= x2 && x1 < axisx.min) {
  1900. if (x2 < axisx.min)
  1901. continue;
  1902. y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1903. x1 = axisx.min;
  1904. }
  1905. else if (x2 <= x1 && x2 < axisx.min) {
  1906. if (x1 < axisx.min)
  1907. continue;
  1908. y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1909. x2 = axisx.min;
  1910. }
  1911. // clip with xmax
  1912. if (x1 >= x2 && x1 > axisx.max) {
  1913. if (x2 > axisx.max)
  1914. continue;
  1915. y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1916. x1 = axisx.max;
  1917. }
  1918. else if (x2 >= x1 && x2 > axisx.max) {
  1919. if (x1 > axisx.max)
  1920. continue;
  1921. y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1922. x2 = axisx.max;
  1923. }
  1924. if (x1 != prevx || y1 != prevy)
  1925. ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
  1926. prevx = x2;
  1927. prevy = y2;
  1928. ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
  1929. }
  1930. ctx.stroke();
  1931. }
  1932. function plotLineArea(datapoints, axisx, axisy) {
  1933. var points = datapoints.points,
  1934. ps = datapoints.pointsize,
  1935. bottom = Math.min(Math.max(0, axisy.min), axisy.max),
  1936. i = 0, top, areaOpen = false,
  1937. ypos = 1, segmentStart = 0, segmentEnd = 0;
  1938. // we process each segment in two turns, first forward
  1939. // direction to sketch out top, then once we hit the
  1940. // end we go backwards to sketch the bottom
  1941. while (true) {
  1942. if (ps > 0 && i > points.length + ps)
  1943. break;
  1944. i += ps; // ps is negative if going backwards
  1945. var x1 = points[i - ps],
  1946. y1 = points[i - ps + ypos],
  1947. x2 = points[i], y2 = points[i + ypos];
  1948. if (areaOpen) {
  1949. if (ps > 0 && x1 != null && x2 == null) {
  1950. // at turning point
  1951. segmentEnd = i;
  1952. ps = -ps;
  1953. ypos = 2;
  1954. continue;
  1955. }
  1956. if (ps < 0 && i == segmentStart + ps) {
  1957. // done with the reverse sweep
  1958. ctx.fill();
  1959. areaOpen = false;
  1960. ps = -ps;
  1961. ypos = 1;
  1962. i = segmentStart = segmentEnd + ps;
  1963. continue;
  1964. }
  1965. }
  1966. if (x1 == null || x2 == null)
  1967. continue;
  1968. // clip x values
  1969. // clip with xmin
  1970. if (x1 <= x2 && x1 < axisx.min) {
  1971. if (x2 < axisx.min)
  1972. continue;
  1973. y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1974. x1 = axisx.min;
  1975. }
  1976. else if (x2 <= x1 && x2 < axisx.min) {
  1977. if (x1 < axisx.min)
  1978. continue;
  1979. y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1980. x2 = axisx.min;
  1981. }
  1982. // clip with xmax
  1983. if (x1 >= x2 && x1 > axisx.max) {
  1984. if (x2 > axisx.max)
  1985. continue;
  1986. y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1987. x1 = axisx.max;
  1988. }
  1989. else if (x2 >= x1 && x2 > axisx.max) {
  1990. if (x1 > axisx.max)
  1991. continue;
  1992. y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1993. x2 = axisx.max;
  1994. }
  1995. if (!areaOpen) {
  1996. // open area
  1997. ctx.beginPath();
  1998. ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
  1999. areaOpen = true;
  2000. }
  2001. // now first check the case where both is outside
  2002. if (y1 >= axisy.max && y2 >= axisy.max) {
  2003. ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
  2004. ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
  2005. continue;
  2006. }
  2007. else if (y1 <= axisy.min && y2 <= axisy.min) {
  2008. ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
  2009. ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
  2010. continue;
  2011. }
  2012. // else it's a bit more complicated, there might
  2013. // be a flat maxed out rectangle first, then a
  2014. // triangular cutout or reverse; to find these
  2015. // keep track of the current x values
  2016. var x1old = x1, x2old = x2;
  2017. // clip the y values, without shortcutting, we
  2018. // go through all cases in turn
  2019. // clip with ymin
  2020. if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
  2021. x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  2022. y1 = axisy.min;
  2023. }
  2024. else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
  2025. x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  2026. y2 = axisy.min;
  2027. }
  2028. // clip with ymax
  2029. if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
  2030. x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  2031. y1 = axisy.max;
  2032. }
  2033. else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
  2034. x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  2035. y2 = axisy.max;
  2036. }
  2037. // if the x value was changed we got a rectangle
  2038. // to fill
  2039. if (x1 != x1old) {
  2040. ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
  2041. // it goes to (x1, y1), but we fill that below
  2042. }
  2043. // fill triangular section, this sometimes result
  2044. // in redundant points if (x1, y1) hasn't changed
  2045. // from previous line to, but we just ignore that
  2046. ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
  2047. ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
  2048. // fill the other rectangle if it's there
  2049. if (x2 != x2old) {
  2050. ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
  2051. ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
  2052. }
  2053. }
  2054. }
  2055. ctx.save();
  2056. ctx.translate(plotOffset.left, plotOffset.top);
  2057. ctx.lineJoin = "round";
  2058. var lw = series.lines.lineWidth,
  2059. sw = series.shadowSize;
  2060. // FIXME: consider another form of shadow when filling is turned on
  2061. if (lw > 0 && sw > 0) {
  2062. // draw shadow as a thick and thin line with transparency
  2063. ctx.lineWidth = sw;
  2064. ctx.strokeStyle = "rgba(0,0,0,0.1)";
  2065. // position shadow at angle from the mid of line
  2066. var angle = Math.PI/18;
  2067. plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
  2068. ctx.lineWidth = sw/2;
  2069. plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
  2070. }
  2071. ctx.lineWidth = lw;
  2072. ctx.strokeStyle = series.color;
  2073. var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
  2074. if (fillStyle) {
  2075. ctx.fillStyle = fillStyle;
  2076. plotLineArea(series.datapoints, series.xaxis, series.yaxis);
  2077. }
  2078. if (lw > 0)
  2079. plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
  2080. ctx.restore();
  2081. }
  2082. function drawSeriesPoints(series) {
  2083. function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
  2084. var points = datapoints.points, ps = datapoints.pointsize;
  2085. for (var i = 0; i < points.length; i += ps) {
  2086. var x = points[i], y = points[i + 1];
  2087. if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
  2088. continue;
  2089. ctx.beginPath();
  2090. x = axisx.p2c(x);
  2091. y = axisy.p2c(y) + offset;
  2092. if (symbol == "circle")
  2093. ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
  2094. else
  2095. symbol(ctx, x, y, radius, shadow);
  2096. ctx.closePath();
  2097. if (fillStyle) {
  2098. ctx.fillStyle = fillStyle;
  2099. ctx.fill();
  2100. }
  2101. ctx.stroke();
  2102. }
  2103. }
  2104. ctx.save();
  2105. ctx.translate(plotOffset.left, plotOffset.top);
  2106. var lw = series.points.lineWidth,
  2107. sw = series.shadowSize,
  2108. radius = series.points.radius,
  2109. symbol = series.points.symbol;
  2110. // If the user sets the line width to 0, we change it to a very
  2111. // small value. A line width of 0 seems to force the default of 1.
  2112. // Doing the conditional here allows the shadow setting to still be
  2113. // optional even with a lineWidth of 0.
  2114. if( lw == 0 )
  2115. lw = 0.0001;
  2116. if (lw > 0 && sw > 0) {
  2117. // draw shadow in two steps
  2118. var w = sw / 2;
  2119. ctx.lineWidth = w;
  2120. ctx.strokeStyle = "rgba(0,0,0,0.1)";
  2121. plotPoints(series.datapoints, radius, null, w + w/2, true,
  2122. series.xaxis, series.yaxis, symbol);
  2123. ctx.strokeStyle = "rgba(0,0,0,0.2)";
  2124. plotPoints(series.datapoints, radius, null, w/2, true,
  2125. series.xaxis, series.yaxis, symbol);
  2126. }
  2127. ctx.lineWidth = lw;
  2128. ctx.strokeStyle = series.color;
  2129. plotPoints(series.datapoints, radius,
  2130. getFillStyle(series.points, series.color), 0, false,
  2131. series.xaxis, series.yaxis, symbol);
  2132. ctx.restore();
  2133. }
  2134. function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
  2135. var left, right, bottom, top,
  2136. drawLeft, drawRight, drawTop, drawBottom,
  2137. tmp;
  2138. // in horizontal mode, we start the bar from the left
  2139. // instead of from the bottom so it appears to be
  2140. // horizontal rather than vertical
  2141. if (horizontal) {
  2142. drawBottom = drawRight = drawTop = true;
  2143. drawLeft = false;
  2144. left = b;
  2145. right = x;
  2146. top = y + barLeft;
  2147. bottom = y + barRight;
  2148. // account for negative bars
  2149. if (right < left) {
  2150. tmp = right;
  2151. right = left;
  2152. left = tmp;
  2153. drawLeft = true;
  2154. drawRight = false;
  2155. }
  2156. }
  2157. else {
  2158. drawLeft = drawRight = drawTop = true;
  2159. drawBottom = false;
  2160. left = x + barLeft;
  2161. right = x + barRight;
  2162. bottom = b;
  2163. top = y;
  2164. // account for negative bars
  2165. if (top < bottom) {
  2166. tmp = top;
  2167. top = bottom;
  2168. bottom = tmp;
  2169. drawBottom = true;
  2170. drawTop = false;
  2171. }
  2172. }
  2173. // clip
  2174. if (right < axisx.min || left > axisx.max ||
  2175. top < axisy.min || bottom > axisy.max)
  2176. return;
  2177. if (left < axisx.min) {
  2178. left = axisx.min;
  2179. drawLeft = false;
  2180. }
  2181. if (right > axisx.max) {
  2182. right = axisx.max;
  2183. drawRight = false;
  2184. }
  2185. if (bottom < axisy.min) {
  2186. bottom = axisy.min;
  2187. drawBottom = false;
  2188. }
  2189. if (top > axisy.max) {
  2190. top = axisy.max;
  2191. drawTop = false;
  2192. }
  2193. left = axisx.p2c(left);
  2194. bottom = axisy.p2c(bottom);
  2195. right = axisx.p2c(right);
  2196. top = axisy.p2c(top);
  2197. // fill the bar
  2198. if (fillStyleCallback) {
  2199. c.fillStyle = fillStyleCallback(bottom, top);
  2200. c.fillRect(left, top, right - left, bottom - top)
  2201. }
  2202. // draw outline
  2203. if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
  2204. c.beginPath();
  2205. // FIXME: inline moveTo is buggy with excanvas
  2206. c.moveTo(left, bottom);
  2207. if (drawLeft)
  2208. c.lineTo(left, top);
  2209. else
  2210. c.moveTo(left, top);
  2211. if (drawTop)
  2212. c.lineTo(right, top);
  2213. else
  2214. c.moveTo(right, top);
  2215. if (drawRight)
  2216. c.lineTo(right, bottom);
  2217. else
  2218. c.moveTo(right, bottom);
  2219. if (drawBottom)
  2220. c.lineTo(left, bottom);
  2221. else
  2222. c.moveTo(left, bottom);
  2223. c.stroke();
  2224. }
  2225. }
  2226. function drawSeriesBars(series) {
  2227. function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
  2228. var points = datapoints.points, ps = datapoints.pointsize;
  2229. for (var i = 0; i < points.length; i += ps) {
  2230. if (points[i] == null)
  2231. continue;
  2232. drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
  2233. }
  2234. }
  2235. ctx.save();
  2236. ctx.translate(plotOffset.left, plotOffset.top);
  2237. // FIXME: figure out a way to add shadows (for instance along the right edge)
  2238. ctx.lineWidth = series.bars.lineWidth;
  2239. ctx.strokeStyle = series.color;
  2240. var barLeft;
  2241. switch (series.bars.align) {
  2242. case "left":
  2243. barLeft = 0;
  2244. break;
  2245. case "right":
  2246. barLeft = -series.bars.barWidth;
  2247. break;
  2248. default:
  2249. barLeft = -series.bars.barWidth / 2;
  2250. }
  2251. var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
  2252. plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
  2253. ctx.restore();
  2254. }
  2255. function getFillStyle(filloptions, seriesColor, bottom, top) {
  2256. var fill = filloptions.fill;
  2257. if (!fill)
  2258. return null;
  2259. if (filloptions.fillColor)
  2260. return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
  2261. var c = $.color.parse(seriesColor);
  2262. c.a = typeof fill == "number" ? fill : 0.4;
  2263. c.normalize();
  2264. return c.toString();
  2265. }
  2266. function insertLegend() {
  2267. if (options.legend.container != null) {
  2268. $(options.legend.container).html("");
  2269. } else {
  2270. placeholder.find(".legend").remove();
  2271. }
  2272. if (!options.legend.show) {
  2273. return;
  2274. }
  2275. var fragments = [], entries = [], rowStarted = false,
  2276. lf = options.legend.labelFormatter, s, label;
  2277. // Build a list of legend entries, with each having a label and a color
  2278. for (var i = 0; i < series.length; ++i) {
  2279. s = series[i];
  2280. if (s.label) {
  2281. label = lf ? lf(s.label, s) : s.label;
  2282. if (label) {
  2283. entries.push({
  2284. label: label,
  2285. color: s.color
  2286. });
  2287. }
  2288. }
  2289. }
  2290. // Sort the legend using either the default or a custom comparator
  2291. if (options.legend.sorted) {
  2292. if ($.isFunction(options.legend.sorted)) {
  2293. entries.sort(options.legend.sorted);
  2294. } else if (options.legend.sorted == "reverse") {
  2295. entries.reverse();
  2296. } else {
  2297. var ascending = options.legend.sorted != "descending";
  2298. entries.sort(function(a, b) {
  2299. return a.label == b.label ? 0 : (
  2300. (a.label < b.label) != ascending ? 1 : -1 // Logical XOR
  2301. );
  2302. });
  2303. }
  2304. }
  2305. // Generate markup for the list of entries, in their final order
  2306. for (var i = 0; i < entries.length; ++i) {
  2307. var entry = entries[i];
  2308. if (i % options.legend.noColumns == 0) {
  2309. if (rowStarted)
  2310. fragments.push('</tr>');
  2311. fragments.push('<tr>');
  2312. rowStarted = true;
  2313. }
  2314. fragments.push(
  2315. '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
  2316. '<td class="legendLabel">' + entry.label + '</td>'
  2317. );
  2318. }
  2319. if (rowStarted)
  2320. fragments.push('</tr>');
  2321. if (fragments.length == 0)
  2322. return;
  2323. var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
  2324. if (options.legend.container != null)
  2325. $(options.legend.container).html(table);
  2326. else {
  2327. var pos = "",
  2328. p = options.legend.position,
  2329. m = options.legend.margin;
  2330. if (m[0] == null)
  2331. m = [m, m];
  2332. if (p.charAt(0) == "n")
  2333. pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
  2334. else if (p.charAt(0) == "s")
  2335. pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
  2336. if (p.charAt(1) == "e")
  2337. pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
  2338. else if (p.charAt(1) == "w")
  2339. pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
  2340. var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
  2341. if (options.legend.backgroundOpacity != 0.0) {
  2342. // put in the transparent background
  2343. // separately to avoid blended labels and
  2344. // label boxes
  2345. var c = options.legend.backgroundColor;
  2346. if (c == null) {
  2347. c = options.grid.backgroundColor;
  2348. if (c && typeof c == "string")
  2349. c = $.color.parse(c);
  2350. else
  2351. c = $.color.extract(legend, 'background-color');
  2352. c.a = 1;
  2353. c = c.toString();
  2354. }
  2355. var div = legend.children();
  2356. $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
  2357. }
  2358. }
  2359. }
  2360. // interactive features
  2361. var highlights = [],
  2362. redrawTimeout = null;
  2363. // returns the data item the mouse is over, or null if none is found
  2364. function findNearbyItem(mouseX, mouseY, seriesFilter) {
  2365. var maxDistance = options.grid.mouseActiveRadius,
  2366. smallestDistance = maxDistance * maxDistance + 1,
  2367. item = null, foundPoint = false, i, j, ps;
  2368. for (i = series.length - 1; i >= 0; --i) {
  2369. if (!seriesFilter(series[i]))
  2370. continue;
  2371. var s = series[i],
  2372. axisx = s.xaxis,
  2373. axisy = s.yaxis,
  2374. points = s.datapoints.points,
  2375. mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
  2376. my = axisy.c2p(mouseY),
  2377. maxx = maxDistance / axisx.scale,
  2378. maxy = maxDistance / axisy.scale;
  2379. ps = s.datapoints.pointsize;
  2380. // with inverse transforms, we can't use the maxx/maxy
  2381. // optimization, sadly
  2382. if (axisx.options.inverseTransform)
  2383. maxx = Number.MAX_VALUE;
  2384. if (axisy.options.inverseTransform)
  2385. maxy = Number.MAX_VALUE;
  2386. if (s.lines.show || s.points.show) {
  2387. for (j = 0; j < points.length; j += ps) {
  2388. var x = points[j], y = points[j + 1];
  2389. if (x == null)
  2390. continue;
  2391. // For points and lines, the cursor must be within a
  2392. // certain distance to the data point
  2393. if (x - mx > maxx || x - mx < -maxx ||
  2394. y - my > maxy || y - my < -maxy)
  2395. continue;
  2396. // We have to calculate distances in pixels, not in
  2397. // data units, because the scales of the axes may be different
  2398. var dx = Math.abs(axisx.p2c(x) - mouseX),
  2399. dy = Math.abs(axisy.p2c(y) - mouseY),
  2400. dist = dx * dx + dy * dy; // we save the sqrt
  2401. // use <= to ensure last point takes precedence
  2402. // (last generally means on top of)
  2403. if (dist < smallestDistance) {
  2404. smallestDistance = dist;
  2405. item = [i, j / ps];
  2406. }
  2407. }
  2408. }
  2409. if (s.bars.show && !item) { // no other point can be nearby
  2410. var barLeft, barRight;
  2411. switch (s.bars.align) {
  2412. case "left":
  2413. barLeft = 0;
  2414. break;
  2415. case "right":
  2416. barLeft = -s.bars.barWidth;
  2417. break;
  2418. default:
  2419. barLeft = -s.bars.barWidth / 2;
  2420. }
  2421. barRight = barLeft + s.bars.barWidth;
  2422. for (j = 0; j < points.length; j += ps) {
  2423. var x = points[j], y = points[j + 1], b = points[j + 2];
  2424. if (x == null)
  2425. continue;
  2426. // for a bar graph, the cursor must be inside the bar
  2427. if (series[i].bars.horizontal ?
  2428. (mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
  2429. my >= y + barLeft && my <= y + barRight) :
  2430. (mx >= x + barLeft && mx <= x + barRight &&
  2431. my >= Math.min(b, y) && my <= Math.max(b, y)))
  2432. item = [i, j / ps];
  2433. }
  2434. }
  2435. }
  2436. if (item) {
  2437. i = item[0];
  2438. j = item[1];
  2439. ps = series[i].datapoints.pointsize;
  2440. return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
  2441. dataIndex: j,
  2442. series: series[i],
  2443. seriesIndex: i };
  2444. }
  2445. return null;
  2446. }
  2447. function onMouseMove(e) {
  2448. if (options.grid.hoverable)
  2449. triggerClickHoverEvent("plothover", e,
  2450. function (s) { return s["hoverable"] != false; });
  2451. }
  2452. function onMouseLeave(e) {
  2453. if (options.grid.hoverable)
  2454. triggerClickHoverEvent("plothover", e,
  2455. function (s) { return false; });
  2456. }
  2457. function onClick(e) {
  2458. triggerClickHoverEvent("plotclick", e,
  2459. function (s) { return s["clickable"] != false; });
  2460. }
  2461. // trigger click or hover event (they send the same parameters
  2462. // so we share their code)
  2463. function triggerClickHoverEvent(eventname, event, seriesFilter) {
  2464. var offset = eventHolder.offset(),
  2465. canvasX = event.pageX - offset.left - plotOffset.left,
  2466. canvasY = event.pageY - offset.top - plotOffset.top,
  2467. pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
  2468. pos.pageX = event.pageX;
  2469. pos.pageY = event.pageY;
  2470. var item = findNearbyItem(canvasX, canvasY, seriesFilter);
  2471. if (item) {
  2472. // fill in mouse pos for any listeners out there
  2473. item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
  2474. item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
  2475. }
  2476. if (options.grid.autoHighlight) {
  2477. // clear auto-highlights
  2478. for (var i = 0; i < highlights.length; ++i) {
  2479. var h = highlights[i];
  2480. if (h.auto == eventname &&
  2481. !(item && h.series == item.series &&
  2482. h.point[0] == item.datapoint[0] &&
  2483. h.point[1] == item.datapoint[1]))
  2484. unhighlight(h.series, h.point);
  2485. }
  2486. if (item)
  2487. highlight(item.series, item.datapoint, eventname);
  2488. }
  2489. placeholder.trigger(eventname, [ pos, item ]);
  2490. }
  2491. function triggerRedrawOverlay() {
  2492. var t = options.interaction.redrawOverlayInterval;
  2493. if (t == -1) { // skip event queue
  2494. drawOverlay();
  2495. return;
  2496. }
  2497. if (!redrawTimeout)
  2498. redrawTimeout = setTimeout(drawOverlay, t);
  2499. }
  2500. function drawOverlay() {
  2501. redrawTimeout = null;
  2502. // draw highlights
  2503. octx.save();
  2504. overlay.clear();
  2505. octx.translate(plotOffset.left, plotOffset.top);
  2506. var i, hi;
  2507. for (i = 0; i < highlights.length; ++i) {
  2508. hi = highlights[i];
  2509. if (hi.series.bars.show)
  2510. drawBarHighlight(hi.series, hi.point);
  2511. else
  2512. drawPointHighlight(hi.series, hi.point);
  2513. }
  2514. octx.restore();
  2515. executeHooks(hooks.drawOverlay, [octx]);
  2516. }
  2517. function highlight(s, point, auto) {
  2518. if (typeof s == "number")
  2519. s = series[s];
  2520. if (typeof point == "number") {
  2521. var ps = s.datapoints.pointsize;
  2522. point = s.datapoints.points.slice(ps * point, ps * (point + 1));
  2523. }
  2524. var i = indexOfHighlight(s, point);
  2525. if (i == -1) {
  2526. highlights.push({ series: s, point: point, auto: auto });
  2527. triggerRedrawOverlay();
  2528. }
  2529. else if (!auto)
  2530. highlights[i].auto = false;
  2531. }
  2532. function unhighlight(s, point) {
  2533. if (s == null && point == null) {
  2534. highlights = [];
  2535. triggerRedrawOverlay();
  2536. return;
  2537. }
  2538. if (typeof s == "number")
  2539. s = series[s];
  2540. if (typeof point == "number") {
  2541. var ps = s.datapoints.pointsize;
  2542. point = s.datapoints.points.slice(ps * point, ps * (point + 1));
  2543. }
  2544. var i = indexOfHighlight(s, point);
  2545. if (i != -1) {
  2546. highlights.splice(i, 1);
  2547. triggerRedrawOverlay();
  2548. }
  2549. }
  2550. function indexOfHighlight(s, p) {
  2551. for (var i = 0; i < highlights.length; ++i) {
  2552. var h = highlights[i];
  2553. if (h.series == s && h.point[0] == p[0]
  2554. && h.point[1] == p[1])
  2555. return i;
  2556. }
  2557. return -1;
  2558. }
  2559. function drawPointHighlight(series, point) {
  2560. var x = point[0], y = point[1],
  2561. axisx = series.xaxis, axisy = series.yaxis,
  2562. highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
  2563. if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
  2564. return;
  2565. var pointRadius = series.points.radius + series.points.lineWidth / 2;
  2566. octx.lineWidth = pointRadius;
  2567. octx.strokeStyle = highlightColor;
  2568. var radius = 1.5 * pointRadius;
  2569. x = axisx.p2c(x);
  2570. y = axisy.p2c(y);
  2571. octx.beginPath();
  2572. if (series.points.symbol == "circle")
  2573. octx.arc(x, y, radius, 0, 2 * Math.PI, false);
  2574. else
  2575. series.points.symbol(octx, x, y, radius, false);
  2576. octx.closePath();
  2577. octx.stroke();
  2578. }
  2579. function drawBarHighlight(series, point) {
  2580. var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
  2581. fillStyle = highlightColor,
  2582. barLeft;
  2583. switch (series.bars.align) {
  2584. case "left":
  2585. barLeft = 0;
  2586. break;
  2587. case "right":
  2588. barLeft = -series.bars.barWidth;
  2589. break;
  2590. default:
  2591. barLeft = -series.bars.barWidth / 2;
  2592. }
  2593. octx.lineWidth = series.bars.lineWidth;
  2594. octx.strokeStyle = highlightColor;
  2595. drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
  2596. function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
  2597. }
  2598. function getColorOrGradient(spec, bottom, top, defaultColor) {
  2599. if (typeof spec == "string")
  2600. return spec;
  2601. else {
  2602. // assume this is a gradient spec; IE currently only
  2603. // supports a simple vertical gradient properly, so that's
  2604. // what we support too
  2605. var gradient = ctx.createLinearGradient(0, top, 0, bottom);
  2606. for (var i = 0, l = spec.colors.length; i < l; ++i) {
  2607. var c = spec.colors[i];
  2608. if (typeof c != "string") {
  2609. var co = $.color.parse(defaultColor);
  2610. if (c.brightness != null)
  2611. co = co.scale('rgb', c.brightness);
  2612. if (c.opacity != null)
  2613. co.a *= c.opacity;
  2614. c = co.toString();
  2615. }
  2616. gradient.addColorStop(i / (l - 1), c);
  2617. }
  2618. return gradient;
  2619. }
  2620. }
  2621. }
  2622. // Add the plot function to the top level of the jQuery object
  2623. $.plot = function(placeholder, data, options) {
  2624. //var t0 = new Date();
  2625. var plot = new Plot($(placeholder), data, options, $.plot.plugins);
  2626. //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
  2627. return plot;
  2628. };
  2629. $.plot.version = "0.8.3";
  2630. $.plot.plugins = [];
  2631. // Also add the plot function as a chainable property
  2632. $.fn.plot = function(data, options) {
  2633. return this.each(function() {
  2634. $.plot(this, data, options);
  2635. });
  2636. };
  2637. // round to nearby lower multiple of base
  2638. function floorInBase(n, base) {
  2639. return base * Math.floor(n / base);
  2640. }
  2641. })(jQuery);
  2642. /* Pretty handling of time axes.
  2643. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  2644. Licensed under the MIT license.
  2645. Set axis.mode to "time" to enable. See the section "Time series data" in
  2646. API.txt for details.
  2647. */
  2648. (function($) {
  2649. var options = {
  2650. xaxis: {
  2651. timezone: null, // "browser" for local to the client or timezone for timezone-js
  2652. timeformat: null, // format string to use
  2653. twelveHourClock: false, // 12 or 24 time in time mode
  2654. monthNames: null // list of names of months
  2655. }
  2656. };
  2657. // round to nearby lower multiple of base
  2658. function floorInBase(n, base) {
  2659. return base * Math.floor(n / base);
  2660. }
  2661. // Returns a string with the date d formatted according to fmt.
  2662. // A subset of the Open Group's strftime format is supported.
  2663. function formatDate(d, fmt, monthNames, dayNames) {
  2664. if (typeof d.strftime == "function") {
  2665. return d.strftime(fmt);
  2666. }
  2667. var leftPad = function(n, pad) {
  2668. n = "" + n;
  2669. pad = "" + (pad == null ? "0" : pad);
  2670. return n.length == 1 ? pad + n : n;
  2671. };
  2672. var r = [];
  2673. var escape = false;
  2674. var hours = d.getHours();
  2675. var isAM = hours < 12;
  2676. if (monthNames == null) {
  2677. monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  2678. }
  2679. if (dayNames == null) {
  2680. dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  2681. }
  2682. var hours12;
  2683. if (hours > 12) {
  2684. hours12 = hours - 12;
  2685. } else if (hours == 0) {
  2686. hours12 = 12;
  2687. } else {
  2688. hours12 = hours;
  2689. }
  2690. for (var i = 0; i < fmt.length; ++i) {
  2691. var c = fmt.charAt(i);
  2692. if (escape) {
  2693. switch (c) {
  2694. case 'a': c = "" + dayNames[d.getDay()]; break;
  2695. case 'b': c = "" + monthNames[d.getMonth()]; break;
  2696. case 'd': c = leftPad(d.getDate()); break;
  2697. case 'e': c = leftPad(d.getDate(), " "); break;
  2698. case 'h': // For back-compat with 0.7; remove in 1.0
  2699. case 'H': c = leftPad(hours); break;
  2700. case 'I': c = leftPad(hours12); break;
  2701. case 'l': c = leftPad(hours12, " "); break;
  2702. case 'm': c = leftPad(d.getMonth() + 1); break;
  2703. case 'M': c = leftPad(d.getMinutes()); break;
  2704. // quarters not in Open Group's strftime specification
  2705. case 'q':
  2706. c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
  2707. case 'S': c = leftPad(d.getSeconds()); break;
  2708. case 'y': c = leftPad(d.getFullYear() % 100); break;
  2709. case 'Y': c = "" + d.getFullYear(); break;
  2710. case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
  2711. case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
  2712. case 'w': c = "" + d.getDay(); break;
  2713. }
  2714. r.push(c);
  2715. escape = false;
  2716. } else {
  2717. if (c == "%") {
  2718. escape = true;
  2719. } else {
  2720. r.push(c);
  2721. }
  2722. }
  2723. }
  2724. return r.join("");
  2725. }
  2726. // To have a consistent view of time-based data independent of which time
  2727. // zone the client happens to be in we need a date-like object independent
  2728. // of time zones. This is done through a wrapper that only calls the UTC
  2729. // versions of the accessor methods.
  2730. function makeUtcWrapper(d) {
  2731. function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
  2732. sourceObj[sourceMethod] = function() {
  2733. return targetObj[targetMethod].apply(targetObj, arguments);
  2734. };
  2735. };
  2736. var utc = {
  2737. date: d
  2738. };
  2739. // support strftime, if found
  2740. if (d.strftime != undefined) {
  2741. addProxyMethod(utc, "strftime", d, "strftime");
  2742. }
  2743. addProxyMethod(utc, "getTime", d, "getTime");
  2744. addProxyMethod(utc, "setTime", d, "setTime");
  2745. var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
  2746. for (var p = 0; p < props.length; p++) {
  2747. addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
  2748. addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
  2749. }
  2750. return utc;
  2751. };
  2752. // select time zone strategy. This returns a date-like object tied to the
  2753. // desired timezone
  2754. function dateGenerator(ts, opts) {
  2755. if (opts.timezone == "browser") {
  2756. return new Date(ts);
  2757. } else if (!opts.timezone || opts.timezone == "utc") {
  2758. return makeUtcWrapper(new Date(ts));
  2759. } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
  2760. var d = new timezoneJS.Date();
  2761. // timezone-js is fickle, so be sure to set the time zone before
  2762. // setting the time.
  2763. d.setTimezone(opts.timezone);
  2764. d.setTime(ts);
  2765. return d;
  2766. } else {
  2767. return makeUtcWrapper(new Date(ts));
  2768. }
  2769. }
  2770. // map of app. size of time units in milliseconds
  2771. var timeUnitSize = {
  2772. "second": 1000,
  2773. "minute": 60 * 1000,
  2774. "hour": 60 * 60 * 1000,
  2775. "day": 24 * 60 * 60 * 1000,
  2776. "month": 30 * 24 * 60 * 60 * 1000,
  2777. "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
  2778. "year": 365.2425 * 24 * 60 * 60 * 1000
  2779. };
  2780. // the allowed tick sizes, after 1 year we use
  2781. // an integer algorithm
  2782. var baseSpec = [
  2783. [1, "second"], [2, "second"], [5, "second"], [10, "second"],
  2784. [30, "second"],
  2785. [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
  2786. [30, "minute"],
  2787. [1, "hour"], [2, "hour"], [4, "hour"],
  2788. [8, "hour"], [12, "hour"],
  2789. [1, "day"], [2, "day"], [3, "day"],
  2790. [0.25, "month"], [0.5, "month"], [1, "month"],
  2791. [2, "month"]
  2792. ];
  2793. // we don't know which variant(s) we'll need yet, but generating both is
  2794. // cheap
  2795. var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
  2796. [1, "year"]]);
  2797. var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
  2798. [1, "year"]]);
  2799. function init(plot) {
  2800. plot.hooks.processOptions.push(function (plot, options) {
  2801. $.each(plot.getAxes(), function(axisName, axis) {
  2802. var opts = axis.options;
  2803. if (opts.mode == "time") {
  2804. axis.tickGenerator = function(axis) {
  2805. var ticks = [];
  2806. var d = dateGenerator(axis.min, opts);
  2807. var minSize = 0;
  2808. // make quarter use a possibility if quarters are
  2809. // mentioned in either of these options
  2810. var spec = (opts.tickSize && opts.tickSize[1] ===
  2811. "quarter") ||
  2812. (opts.minTickSize && opts.minTickSize[1] ===
  2813. "quarter") ? specQuarters : specMonths;
  2814. if (opts.minTickSize != null) {
  2815. if (typeof opts.tickSize == "number") {
  2816. minSize = opts.tickSize;
  2817. } else {
  2818. minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
  2819. }
  2820. }
  2821. for (var i = 0; i < spec.length - 1; ++i) {
  2822. if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
  2823. + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
  2824. && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
  2825. break;
  2826. }
  2827. }
  2828. var size = spec[i][0];
  2829. var unit = spec[i][1];
  2830. // special-case the possibility of several years
  2831. if (unit == "year") {
  2832. // if given a minTickSize in years, just use it,
  2833. // ensuring that it's an integer
  2834. if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
  2835. size = Math.floor(opts.minTickSize[0]);
  2836. } else {
  2837. var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
  2838. var norm = (axis.delta / timeUnitSize.year) / magn;
  2839. if (norm < 1.5) {
  2840. size = 1;
  2841. } else if (norm < 3) {
  2842. size = 2;
  2843. } else if (norm < 7.5) {
  2844. size = 5;
  2845. } else {
  2846. size = 10;
  2847. }
  2848. size *= magn;
  2849. }
  2850. // minimum size for years is 1
  2851. if (size < 1) {
  2852. size = 1;
  2853. }
  2854. }
  2855. axis.tickSize = opts.tickSize || [size, unit];
  2856. var tickSize = axis.tickSize[0];
  2857. unit = axis.tickSize[1];
  2858. var step = tickSize * timeUnitSize[unit];
  2859. if (unit == "second") {
  2860. d.setSeconds(floorInBase(d.getSeconds(), tickSize));
  2861. } else if (unit == "minute") {
  2862. d.setMinutes(floorInBase(d.getMinutes(), tickSize));
  2863. } else if (unit == "hour") {
  2864. d.setHours(floorInBase(d.getHours(), tickSize));
  2865. } else if (unit == "month") {
  2866. d.setMonth(floorInBase(d.getMonth(), tickSize));
  2867. } else if (unit == "quarter") {
  2868. d.setMonth(3 * floorInBase(d.getMonth() / 3,
  2869. tickSize));
  2870. } else if (unit == "year") {
  2871. d.setFullYear(floorInBase(d.getFullYear(), tickSize));
  2872. }
  2873. // reset smaller components
  2874. d.setMilliseconds(0);
  2875. if (step >= timeUnitSize.minute) {
  2876. d.setSeconds(0);
  2877. }
  2878. if (step >= timeUnitSize.hour) {
  2879. d.setMinutes(0);
  2880. }
  2881. if (step >= timeUnitSize.day) {
  2882. d.setHours(0);
  2883. }
  2884. if (step >= timeUnitSize.day * 4) {
  2885. d.setDate(1);
  2886. }
  2887. if (step >= timeUnitSize.month * 2) {
  2888. d.setMonth(floorInBase(d.getMonth(), 3));
  2889. }
  2890. if (step >= timeUnitSize.quarter * 2) {
  2891. d.setMonth(floorInBase(d.getMonth(), 6));
  2892. }
  2893. if (step >= timeUnitSize.year) {
  2894. d.setMonth(0);
  2895. }
  2896. var carry = 0;
  2897. var v = Number.NaN;
  2898. var prev;
  2899. do {
  2900. prev = v;
  2901. v = d.getTime();
  2902. ticks.push(v);
  2903. if (unit == "month" || unit == "quarter") {
  2904. if (tickSize < 1) {
  2905. // a bit complicated - we'll divide the
  2906. // month/quarter up but we need to take
  2907. // care of fractions so we don't end up in
  2908. // the middle of a day
  2909. d.setDate(1);
  2910. var start = d.getTime();
  2911. d.setMonth(d.getMonth() +
  2912. (unit == "quarter" ? 3 : 1));
  2913. var end = d.getTime();
  2914. d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
  2915. carry = d.getHours();
  2916. d.setHours(0);
  2917. } else {
  2918. d.setMonth(d.getMonth() +
  2919. tickSize * (unit == "quarter" ? 3 : 1));
  2920. }
  2921. } else if (unit == "year") {
  2922. d.setFullYear(d.getFullYear() + tickSize);
  2923. } else {
  2924. d.setTime(v + step);
  2925. }
  2926. } while (v < axis.max && v != prev);
  2927. return ticks;
  2928. };
  2929. axis.tickFormatter = function (v, axis) {
  2930. var d = dateGenerator(v, axis.options);
  2931. // first check global format
  2932. if (opts.timeformat != null) {
  2933. return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
  2934. }
  2935. // possibly use quarters if quarters are mentioned in
  2936. // any of these places
  2937. var useQuarters = (axis.options.tickSize &&
  2938. axis.options.tickSize[1] == "quarter") ||
  2939. (axis.options.minTickSize &&
  2940. axis.options.minTickSize[1] == "quarter");
  2941. var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
  2942. var span = axis.max - axis.min;
  2943. var suffix = (opts.twelveHourClock) ? " %p" : "";
  2944. var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
  2945. var fmt;
  2946. if (t < timeUnitSize.minute) {
  2947. fmt = hourCode + ":%M:%S" + suffix;
  2948. } else if (t < timeUnitSize.day) {
  2949. if (span < 2 * timeUnitSize.day) {
  2950. fmt = hourCode + ":%M" + suffix;
  2951. } else {
  2952. fmt = "%b %d " + hourCode + ":%M" + suffix;
  2953. }
  2954. } else if (t < timeUnitSize.month) {
  2955. fmt = "%b %d";
  2956. } else if ((useQuarters && t < timeUnitSize.quarter) ||
  2957. (!useQuarters && t < timeUnitSize.year)) {
  2958. if (span < timeUnitSize.year) {
  2959. fmt = "%b";
  2960. } else {
  2961. fmt = "%b %Y";
  2962. }
  2963. } else if (useQuarters && t < timeUnitSize.year) {
  2964. if (span < timeUnitSize.year) {
  2965. fmt = "Q%q";
  2966. } else {
  2967. fmt = "Q%q %Y";
  2968. }
  2969. } else {
  2970. fmt = "%Y";
  2971. }
  2972. var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
  2973. return rt;
  2974. };
  2975. }
  2976. });
  2977. });
  2978. }
  2979. $.plot.plugins.push({
  2980. init: init,
  2981. options: options,
  2982. name: 'time',
  2983. version: '1.0'
  2984. });
  2985. // Time-axis support used to be in Flot core, which exposed the
  2986. // formatDate function on the plot object. Various plugins depend
  2987. // on the function, so we need to re-expose it here.
  2988. $.plot.formatDate = formatDate;
  2989. $.plot.dateGenerator = dateGenerator;
  2990. })(jQuery);
  2991. /* Flot plugin for automatically redrawing plots as the placeholder resizes.
  2992. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  2993. Licensed under the MIT license.
  2994. It works by listening for changes on the placeholder div (through the jQuery
  2995. resize event plugin) - if the size changes, it will redraw the plot.
  2996. There are no options. If you need to disable the plugin for some plots, you
  2997. can just fix the size of their placeholders.
  2998. */
  2999. /* Inline dependency:
  3000. * jQuery resize event - v1.1 - 3/14/2010
  3001. * http://benalman.com/projects/jquery-resize-plugin/
  3002. *
  3003. * Copyright (c) 2010 "Cowboy" Ben Alman
  3004. * Dual licensed under the MIT and GPL licenses.
  3005. * http://benalman.com/about/license/
  3006. */
  3007. (function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
  3008. (function ($) {
  3009. var options = { }; // no options
  3010. function init(plot) {
  3011. function onResize() {
  3012. var placeholder = plot.getPlaceholder();
  3013. // somebody might have hidden us and we can't plot
  3014. // when we don't have the dimensions
  3015. if (placeholder.width() == 0 || placeholder.height() == 0)
  3016. return;
  3017. plot.resize();
  3018. plot.setupGrid();
  3019. plot.draw();
  3020. }
  3021. function bindEvents(plot, eventHolder) {
  3022. plot.getPlaceholder().resize(onResize);
  3023. }
  3024. function shutdown(plot, eventHolder) {
  3025. plot.getPlaceholder().unbind("resize", onResize);
  3026. }
  3027. plot.hooks.bindEvents.push(bindEvents);
  3028. plot.hooks.shutdown.push(shutdown);
  3029. }
  3030. $.plot.plugins.push({
  3031. init: init,
  3032. options: options,
  3033. name: 'resize',
  3034. version: '1.0'
  3035. });
  3036. })(jQuery);
  3037. /* Flot plugin for rendering pie charts.
  3038. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3039. Licensed under the MIT license.
  3040. The plugin assumes that each series has a single data value, and that each
  3041. value is a positive integer or zero. Negative numbers don't make sense for a
  3042. pie chart, and have unpredictable results. The values do NOT need to be
  3043. passed in as percentages; the plugin will calculate the total and per-slice
  3044. percentages internally.
  3045. * Created by Brian Medendorp
  3046. * Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars
  3047. The plugin supports these options:
  3048. series: {
  3049. pie: {
  3050. show: true/false
  3051. radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
  3052. innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
  3053. startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
  3054. tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
  3055. offset: {
  3056. top: integer value to move the pie up or down
  3057. left: integer value to move the pie left or right, or 'auto'
  3058. },
  3059. stroke: {
  3060. color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
  3061. width: integer pixel width of the stroke
  3062. },
  3063. label: {
  3064. show: true/false, or 'auto'
  3065. formatter: a user-defined function that modifies the text/style of the label text
  3066. radius: 0-1 for percentage of fullsize, or a specified pixel length
  3067. background: {
  3068. color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
  3069. opacity: 0-1
  3070. },
  3071. threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
  3072. },
  3073. combine: {
  3074. threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
  3075. color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
  3076. label: any text value of what the combined slice should be labeled
  3077. }
  3078. highlight: {
  3079. opacity: 0-1
  3080. }
  3081. }
  3082. }
  3083. More detail and specific examples can be found in the included HTML file.
  3084. */
  3085. (function($) {
  3086. // Maximum redraw attempts when fitting labels within the plot
  3087. var REDRAW_ATTEMPTS = 10;
  3088. // Factor by which to shrink the pie when fitting labels within the plot
  3089. var REDRAW_SHRINK = 0.95;
  3090. function init(plot) {
  3091. var canvas = null,
  3092. target = null,
  3093. options = null,
  3094. maxRadius = null,
  3095. centerLeft = null,
  3096. centerTop = null,
  3097. processed = false,
  3098. ctx = null;
  3099. // interactive variables
  3100. var highlights = [];
  3101. // add hook to determine if pie plugin in enabled, and then perform necessary operations
  3102. plot.hooks.processOptions.push(function(plot, options) {
  3103. if (options.series.pie.show) {
  3104. options.grid.show = false;
  3105. // set labels.show
  3106. if (options.series.pie.label.show == "auto") {
  3107. if (options.legend.show) {
  3108. options.series.pie.label.show = false;
  3109. } else {
  3110. options.series.pie.label.show = true;
  3111. }
  3112. }
  3113. // set radius
  3114. if (options.series.pie.radius == "auto") {
  3115. if (options.series.pie.label.show) {
  3116. options.series.pie.radius = 3/4;
  3117. } else {
  3118. options.series.pie.radius = 1;
  3119. }
  3120. }
  3121. // ensure sane tilt
  3122. if (options.series.pie.tilt > 1) {
  3123. options.series.pie.tilt = 1;
  3124. } else if (options.series.pie.tilt < 0) {
  3125. options.series.pie.tilt = 0;
  3126. }
  3127. }
  3128. });
  3129. plot.hooks.bindEvents.push(function(plot, eventHolder) {
  3130. var options = plot.getOptions();
  3131. if (options.series.pie.show) {
  3132. if (options.grid.hoverable) {
  3133. eventHolder.unbind("mousemove").mousemove(onMouseMove);
  3134. }
  3135. if (options.grid.clickable) {
  3136. eventHolder.unbind("click").click(onClick);
  3137. }
  3138. }
  3139. });
  3140. plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) {
  3141. var options = plot.getOptions();
  3142. if (options.series.pie.show) {
  3143. processDatapoints(plot, series, data, datapoints);
  3144. }
  3145. });
  3146. plot.hooks.drawOverlay.push(function(plot, octx) {
  3147. var options = plot.getOptions();
  3148. if (options.series.pie.show) {
  3149. drawOverlay(plot, octx);
  3150. }
  3151. });
  3152. plot.hooks.draw.push(function(plot, newCtx) {
  3153. var options = plot.getOptions();
  3154. if (options.series.pie.show) {
  3155. draw(plot, newCtx);
  3156. }
  3157. });
  3158. function processDatapoints(plot, series, datapoints) {
  3159. if (!processed) {
  3160. processed = true;
  3161. canvas = plot.getCanvas();
  3162. target = $(canvas).parent();
  3163. options = plot.getOptions();
  3164. plot.setData(combine(plot.getData()));
  3165. }
  3166. }
  3167. function combine(data) {
  3168. var total = 0,
  3169. combined = 0,
  3170. numCombined = 0,
  3171. color = options.series.pie.combine.color,
  3172. newdata = [];
  3173. // Fix up the raw data from Flot, ensuring the data is numeric
  3174. for (var i = 0; i < data.length; ++i) {
  3175. var value = data[i].data;
  3176. // If the data is an array, we'll assume that it's a standard
  3177. // Flot x-y pair, and are concerned only with the second value.
  3178. // Note how we use the original array, rather than creating a
  3179. // new one; this is more efficient and preserves any extra data
  3180. // that the user may have stored in higher indexes.
  3181. if ($.isArray(value) && value.length == 1) {
  3182. value = value[0];
  3183. }
  3184. if ($.isArray(value)) {
  3185. // Equivalent to $.isNumeric() but compatible with jQuery < 1.7
  3186. if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) {
  3187. value[1] = +value[1];
  3188. } else {
  3189. value[1] = 0;
  3190. }
  3191. } else if (!isNaN(parseFloat(value)) && isFinite(value)) {
  3192. value = [1, +value];
  3193. } else {
  3194. value = [1, 0];
  3195. }
  3196. data[i].data = [value];
  3197. }
  3198. // Sum up all the slices, so we can calculate percentages for each
  3199. for (var i = 0; i < data.length; ++i) {
  3200. total += data[i].data[0][1];
  3201. }
  3202. // Count the number of slices with percentages below the combine
  3203. // threshold; if it turns out to be just one, we won't combine.
  3204. for (var i = 0; i < data.length; ++i) {
  3205. var value = data[i].data[0][1];
  3206. if (value / total <= options.series.pie.combine.threshold) {
  3207. combined += value;
  3208. numCombined++;
  3209. if (!color) {
  3210. color = data[i].color;
  3211. }
  3212. }
  3213. }
  3214. for (var i = 0; i < data.length; ++i) {
  3215. var value = data[i].data[0][1];
  3216. if (numCombined < 2 || value / total > options.series.pie.combine.threshold) {
  3217. newdata.push(
  3218. $.extend(data[i], { /* extend to allow keeping all other original data values
  3219. and using them e.g. in labelFormatter. */
  3220. data: [[1, value]],
  3221. color: data[i].color,
  3222. label: data[i].label,
  3223. angle: value * Math.PI * 2 / total,
  3224. percent: value / (total / 100)
  3225. })
  3226. );
  3227. }
  3228. }
  3229. if (numCombined > 1) {
  3230. newdata.push({
  3231. data: [[1, combined]],
  3232. color: color,
  3233. label: options.series.pie.combine.label,
  3234. angle: combined * Math.PI * 2 / total,
  3235. percent: combined / (total / 100)
  3236. });
  3237. }
  3238. return newdata;
  3239. }
  3240. function draw(plot, newCtx) {
  3241. if (!target) {
  3242. return; // if no series were passed
  3243. }
  3244. var canvasWidth = plot.getPlaceholder().width(),
  3245. canvasHeight = plot.getPlaceholder().height(),
  3246. legendWidth = target.children().filter(".legend").children().width() || 0;
  3247. ctx = newCtx;
  3248. // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE!
  3249. // When combining smaller slices into an 'other' slice, we need to
  3250. // add a new series. Since Flot gives plugins no way to modify the
  3251. // list of series, the pie plugin uses a hack where the first call
  3252. // to processDatapoints results in a call to setData with the new
  3253. // list of series, then subsequent processDatapoints do nothing.
  3254. // The plugin-global 'processed' flag is used to control this hack;
  3255. // it starts out false, and is set to true after the first call to
  3256. // processDatapoints.
  3257. // Unfortunately this turns future setData calls into no-ops; they
  3258. // call processDatapoints, the flag is true, and nothing happens.
  3259. // To fix this we'll set the flag back to false here in draw, when
  3260. // all series have been processed, so the next sequence of calls to
  3261. // processDatapoints once again starts out with a slice-combine.
  3262. // This is really a hack; in 0.9 we need to give plugins a proper
  3263. // way to modify series before any processing begins.
  3264. processed = false;
  3265. // calculate maximum radius and center point
  3266. maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2;
  3267. centerTop = canvasHeight / 2 + options.series.pie.offset.top;
  3268. centerLeft = canvasWidth / 2;
  3269. if (options.series.pie.offset.left == "auto") {
  3270. if (options.legend.position.match("w")) {
  3271. centerLeft += legendWidth / 2;
  3272. } else {
  3273. centerLeft -= legendWidth / 2;
  3274. }
  3275. if (centerLeft < maxRadius) {
  3276. centerLeft = maxRadius;
  3277. } else if (centerLeft > canvasWidth - maxRadius) {
  3278. centerLeft = canvasWidth - maxRadius;
  3279. }
  3280. } else {
  3281. centerLeft += options.series.pie.offset.left;
  3282. }
  3283. var slices = plot.getData(),
  3284. attempts = 0;
  3285. // Keep shrinking the pie's radius until drawPie returns true,
  3286. // indicating that all the labels fit, or we try too many times.
  3287. do {
  3288. if (attempts > 0) {
  3289. maxRadius *= REDRAW_SHRINK;
  3290. }
  3291. attempts += 1;
  3292. clear();
  3293. if (options.series.pie.tilt <= 0.8) {
  3294. drawShadow();
  3295. }
  3296. } while (!drawPie() && attempts < REDRAW_ATTEMPTS)
  3297. if (attempts >= REDRAW_ATTEMPTS) {
  3298. clear();
  3299. target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>");
  3300. }
  3301. if (plot.setSeries && plot.insertLegend) {
  3302. plot.setSeries(slices);
  3303. plot.insertLegend();
  3304. }
  3305. // we're actually done at this point, just defining internal functions at this point
  3306. function clear() {
  3307. ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  3308. target.children().filter(".pieLabel, .pieLabelBackground").remove();
  3309. }
  3310. function drawShadow() {
  3311. var shadowLeft = options.series.pie.shadow.left;
  3312. var shadowTop = options.series.pie.shadow.top;
  3313. var edge = 10;
  3314. var alpha = options.series.pie.shadow.alpha;
  3315. var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
  3316. if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) {
  3317. return; // shadow would be outside canvas, so don't draw it
  3318. }
  3319. ctx.save();
  3320. ctx.translate(shadowLeft,shadowTop);
  3321. ctx.globalAlpha = alpha;
  3322. ctx.fillStyle = "#000";
  3323. // center and rotate to starting position
  3324. ctx.translate(centerLeft,centerTop);
  3325. ctx.scale(1, options.series.pie.tilt);
  3326. //radius -= edge;
  3327. for (var i = 1; i <= edge; i++) {
  3328. ctx.beginPath();
  3329. ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
  3330. ctx.fill();
  3331. radius -= i;
  3332. }
  3333. ctx.restore();
  3334. }
  3335. function drawPie() {
  3336. var startAngle = Math.PI * options.series.pie.startAngle;
  3337. var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
  3338. // center and rotate to starting position
  3339. ctx.save();
  3340. ctx.translate(centerLeft,centerTop);
  3341. ctx.scale(1, options.series.pie.tilt);
  3342. //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
  3343. // draw slices
  3344. ctx.save();
  3345. var currentAngle = startAngle;
  3346. for (var i = 0; i < slices.length; ++i) {
  3347. slices[i].startAngle = currentAngle;
  3348. drawSlice(slices[i].angle, slices[i].color, true);
  3349. }
  3350. ctx.restore();
  3351. // draw slice outlines
  3352. if (options.series.pie.stroke.width > 0) {
  3353. ctx.save();
  3354. ctx.lineWidth = options.series.pie.stroke.width;
  3355. currentAngle = startAngle;
  3356. for (var i = 0; i < slices.length; ++i) {
  3357. drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
  3358. }
  3359. ctx.restore();
  3360. }
  3361. // draw donut hole
  3362. drawDonutHole(ctx);
  3363. ctx.restore();
  3364. // Draw the labels, returning true if they fit within the plot
  3365. if (options.series.pie.label.show) {
  3366. return drawLabels();
  3367. } else return true;
  3368. function drawSlice(angle, color, fill) {
  3369. if (angle <= 0 || isNaN(angle)) {
  3370. return;
  3371. }
  3372. if (fill) {
  3373. ctx.fillStyle = color;
  3374. } else {
  3375. ctx.strokeStyle = color;
  3376. ctx.lineJoin = "round";
  3377. }
  3378. ctx.beginPath();
  3379. if (Math.abs(angle - Math.PI * 2) > 0.000000001) {
  3380. ctx.moveTo(0, 0); // Center of the pie
  3381. }
  3382. //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera
  3383. ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false);
  3384. ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false);
  3385. ctx.closePath();
  3386. //ctx.rotate(angle); // This doesn't work properly in Opera
  3387. currentAngle += angle;
  3388. if (fill) {
  3389. ctx.fill();
  3390. } else {
  3391. ctx.stroke();
  3392. }
  3393. }
  3394. function drawLabels() {
  3395. var currentAngle = startAngle;
  3396. var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius;
  3397. for (var i = 0; i < slices.length; ++i) {
  3398. if (slices[i].percent >= options.series.pie.label.threshold * 100) {
  3399. if (!drawLabel(slices[i], currentAngle, i)) {
  3400. return false;
  3401. }
  3402. }
  3403. currentAngle += slices[i].angle;
  3404. }
  3405. return true;
  3406. function drawLabel(slice, startAngle, index) {
  3407. if (slice.data[0][1] == 0) {
  3408. return true;
  3409. }
  3410. // format label text
  3411. var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
  3412. if (lf) {
  3413. text = lf(slice.label, slice);
  3414. } else {
  3415. text = slice.label;
  3416. }
  3417. if (plf) {
  3418. text = plf(text, slice);
  3419. }
  3420. var halfAngle = ((startAngle + slice.angle) + startAngle) / 2;
  3421. var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
  3422. var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
  3423. var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>";
  3424. target.append(html);
  3425. var label = target.children("#pieLabel" + index);
  3426. var labelTop = (y - label.height() / 2);
  3427. var labelLeft = (x - label.width() / 2);
  3428. label.css("top", labelTop);
  3429. label.css("left", labelLeft);
  3430. // check to make sure that the label is not outside the canvas
  3431. if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) {
  3432. return false;
  3433. }
  3434. if (options.series.pie.label.background.opacity != 0) {
  3435. // put in the transparent background separately to avoid blended labels and label boxes
  3436. var c = options.series.pie.label.background.color;
  3437. if (c == null) {
  3438. c = slice.color;
  3439. }
  3440. var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;";
  3441. $("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>")
  3442. .css("opacity", options.series.pie.label.background.opacity)
  3443. .insertBefore(label);
  3444. }
  3445. return true;
  3446. } // end individual label function
  3447. } // end drawLabels function
  3448. } // end drawPie function
  3449. } // end draw function
  3450. // Placed here because it needs to be accessed from multiple locations
  3451. function drawDonutHole(layer) {
  3452. if (options.series.pie.innerRadius > 0) {
  3453. // subtract the center
  3454. layer.save();
  3455. var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
  3456. layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
  3457. layer.beginPath();
  3458. layer.fillStyle = options.series.pie.stroke.color;
  3459. layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
  3460. layer.fill();
  3461. layer.closePath();
  3462. layer.restore();
  3463. // add inner stroke
  3464. layer.save();
  3465. layer.beginPath();
  3466. layer.strokeStyle = options.series.pie.stroke.color;
  3467. layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
  3468. layer.stroke();
  3469. layer.closePath();
  3470. layer.restore();
  3471. // TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
  3472. }
  3473. }
  3474. //-- Additional Interactive related functions --
  3475. function isPointInPoly(poly, pt) {
  3476. for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
  3477. ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
  3478. && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
  3479. && (c = !c);
  3480. return c;
  3481. }
  3482. function findNearbySlice(mouseX, mouseY) {
  3483. var slices = plot.getData(),
  3484. options = plot.getOptions(),
  3485. radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius,
  3486. x, y;
  3487. for (var i = 0; i < slices.length; ++i) {
  3488. var s = slices[i];
  3489. if (s.pie.show) {
  3490. ctx.save();
  3491. ctx.beginPath();
  3492. ctx.moveTo(0, 0); // Center of the pie
  3493. //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
  3494. ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false);
  3495. ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false);
  3496. ctx.closePath();
  3497. x = mouseX - centerLeft;
  3498. y = mouseY - centerTop;
  3499. if (ctx.isPointInPath) {
  3500. if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) {
  3501. ctx.restore();
  3502. return {
  3503. datapoint: [s.percent, s.data],
  3504. dataIndex: 0,
  3505. series: s,
  3506. seriesIndex: i
  3507. };
  3508. }
  3509. } else {
  3510. // excanvas for IE doesn;t support isPointInPath, this is a workaround.
  3511. var p1X = radius * Math.cos(s.startAngle),
  3512. p1Y = radius * Math.sin(s.startAngle),
  3513. p2X = radius * Math.cos(s.startAngle + s.angle / 4),
  3514. p2Y = radius * Math.sin(s.startAngle + s.angle / 4),
  3515. p3X = radius * Math.cos(s.startAngle + s.angle / 2),
  3516. p3Y = radius * Math.sin(s.startAngle + s.angle / 2),
  3517. p4X = radius * Math.cos(s.startAngle + s.angle / 1.5),
  3518. p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5),
  3519. p5X = radius * Math.cos(s.startAngle + s.angle),
  3520. p5Y = radius * Math.sin(s.startAngle + s.angle),
  3521. arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]],
  3522. arrPoint = [x, y];
  3523. // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
  3524. if (isPointInPoly(arrPoly, arrPoint)) {
  3525. ctx.restore();
  3526. return {
  3527. datapoint: [s.percent, s.data],
  3528. dataIndex: 0,
  3529. series: s,
  3530. seriesIndex: i
  3531. };
  3532. }
  3533. }
  3534. ctx.restore();
  3535. }
  3536. }
  3537. return null;
  3538. }
  3539. function onMouseMove(e) {
  3540. triggerClickHoverEvent("plothover", e);
  3541. }
  3542. function onClick(e) {
  3543. triggerClickHoverEvent("plotclick", e);
  3544. }
  3545. // trigger click or hover event (they send the same parameters so we share their code)
  3546. function triggerClickHoverEvent(eventname, e) {
  3547. var offset = plot.offset();
  3548. var canvasX = parseInt(e.pageX - offset.left);
  3549. var canvasY = parseInt(e.pageY - offset.top);
  3550. var item = findNearbySlice(canvasX, canvasY);
  3551. if (options.grid.autoHighlight) {
  3552. // clear auto-highlights
  3553. for (var i = 0; i < highlights.length; ++i) {
  3554. var h = highlights[i];
  3555. if (h.auto == eventname && !(item && h.series == item.series)) {
  3556. unhighlight(h.series);
  3557. }
  3558. }
  3559. }
  3560. // highlight the slice
  3561. if (item) {
  3562. highlight(item.series, eventname);
  3563. }
  3564. // trigger any hover bind events
  3565. var pos = { pageX: e.pageX, pageY: e.pageY };
  3566. target.trigger(eventname, [pos, item]);
  3567. }
  3568. function highlight(s, auto) {
  3569. //if (typeof s == "number") {
  3570. // s = series[s];
  3571. //}
  3572. var i = indexOfHighlight(s);
  3573. if (i == -1) {
  3574. highlights.push({ series: s, auto: auto });
  3575. plot.triggerRedrawOverlay();
  3576. } else if (!auto) {
  3577. highlights[i].auto = false;
  3578. }
  3579. }
  3580. function unhighlight(s) {
  3581. if (s == null) {
  3582. highlights = [];
  3583. plot.triggerRedrawOverlay();
  3584. }
  3585. //if (typeof s == "number") {
  3586. // s = series[s];
  3587. //}
  3588. var i = indexOfHighlight(s);
  3589. if (i != -1) {
  3590. highlights.splice(i, 1);
  3591. plot.triggerRedrawOverlay();
  3592. }
  3593. }
  3594. function indexOfHighlight(s) {
  3595. for (var i = 0; i < highlights.length; ++i) {
  3596. var h = highlights[i];
  3597. if (h.series == s)
  3598. return i;
  3599. }
  3600. return -1;
  3601. }
  3602. function drawOverlay(plot, octx) {
  3603. var options = plot.getOptions();
  3604. var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
  3605. octx.save();
  3606. octx.translate(centerLeft, centerTop);
  3607. octx.scale(1, options.series.pie.tilt);
  3608. for (var i = 0; i < highlights.length; ++i) {
  3609. drawHighlight(highlights[i].series);
  3610. }
  3611. drawDonutHole(octx);
  3612. octx.restore();
  3613. function drawHighlight(series) {
  3614. if (series.angle <= 0 || isNaN(series.angle)) {
  3615. return;
  3616. }
  3617. //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
  3618. octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor
  3619. octx.beginPath();
  3620. if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) {
  3621. octx.moveTo(0, 0); // Center of the pie
  3622. }
  3623. octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false);
  3624. octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false);
  3625. octx.closePath();
  3626. octx.fill();
  3627. }
  3628. }
  3629. } // end init (plugin body)
  3630. // define pie specific options and their default values
  3631. var options = {
  3632. series: {
  3633. pie: {
  3634. show: false,
  3635. radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
  3636. innerRadius: 0, /* for donut */
  3637. startAngle: 3/2,
  3638. tilt: 1,
  3639. shadow: {
  3640. left: 5, // shadow left offset
  3641. top: 15, // shadow top offset
  3642. alpha: 0.02 // shadow alpha
  3643. },
  3644. offset: {
  3645. top: 0,
  3646. left: "auto"
  3647. },
  3648. stroke: {
  3649. color: "#fff",
  3650. width: 1
  3651. },
  3652. label: {
  3653. show: "auto",
  3654. formatter: function(label, slice) {
  3655. return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>";
  3656. }, // formatter function
  3657. radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
  3658. background: {
  3659. color: null,
  3660. opacity: 0
  3661. },
  3662. threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
  3663. },
  3664. combine: {
  3665. threshold: -1, // percentage at which to combine little slices into one larger slice
  3666. color: null, // color to give the new slice (auto-generated if null)
  3667. label: "Other" // label to give the new slice
  3668. },
  3669. highlight: {
  3670. //color: "#fff", // will add this functionality once parseColor is available
  3671. opacity: 0.5
  3672. }
  3673. }
  3674. }
  3675. };
  3676. $.plot.plugins.push({
  3677. init: init,
  3678. options: options,
  3679. name: "pie",
  3680. version: "1.1"
  3681. });
  3682. })(jQuery);
  3683. /* Flot plugin for selecting regions of a plot.
  3684. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3685. Licensed under the MIT license.
  3686. The plugin supports these options:
  3687. selection: {
  3688. mode: null or "x" or "y" or "xy",
  3689. color: color,
  3690. shape: "round" or "miter" or "bevel",
  3691. minSize: number of pixels
  3692. }
  3693. Selection support is enabled by setting the mode to one of "x", "y" or "xy".
  3694. In "x" mode, the user will only be able to specify the x range, similarly for
  3695. "y" mode. For "xy", the selection becomes a rectangle where both ranges can be
  3696. specified. "color" is color of the selection (if you need to change the color
  3697. later on, you can get to it with plot.getOptions().selection.color). "shape"
  3698. is the shape of the corners of the selection.
  3699. "minSize" is the minimum size a selection can be in pixels. This value can
  3700. be customized to determine the smallest size a selection can be and still
  3701. have the selection rectangle be displayed. When customizing this value, the
  3702. fact that it refers to pixels, not axis units must be taken into account.
  3703. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
  3704. minute, setting "minSize" to 1 will not make the minimum selection size 1
  3705. minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
  3706. "plotunselected" events from being fired when the user clicks the mouse without
  3707. dragging.
  3708. When selection support is enabled, a "plotselected" event will be emitted on
  3709. the DOM element you passed into the plot function. The event handler gets a
  3710. parameter with the ranges selected on the axes, like this:
  3711. placeholder.bind( "plotselected", function( event, ranges ) {
  3712. alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
  3713. // similar for yaxis - with multiple axes, the extra ones are in
  3714. // x2axis, x3axis, ...
  3715. });
  3716. The "plotselected" event is only fired when the user has finished making the
  3717. selection. A "plotselecting" event is fired during the process with the same
  3718. parameters as the "plotselected" event, in case you want to know what's
  3719. happening while it's happening,
  3720. A "plotunselected" event with no arguments is emitted when the user clicks the
  3721. mouse to remove the selection. As stated above, setting "minSize" to 0 will
  3722. destroy this behavior.
  3723. The plugin allso adds the following methods to the plot object:
  3724. - setSelection( ranges, preventEvent )
  3725. Set the selection rectangle. The passed in ranges is on the same form as
  3726. returned in the "plotselected" event. If the selection mode is "x", you
  3727. should put in either an xaxis range, if the mode is "y" you need to put in
  3728. an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
  3729. this:
  3730. setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
  3731. setSelection will trigger the "plotselected" event when called. If you don't
  3732. want that to happen, e.g. if you're inside a "plotselected" handler, pass
  3733. true as the second parameter. If you are using multiple axes, you can
  3734. specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
  3735. xaxis, the plugin picks the first one it sees.
  3736. - clearSelection( preventEvent )
  3737. Clear the selection rectangle. Pass in true to avoid getting a
  3738. "plotunselected" event.
  3739. - getSelection()
  3740. Returns the current selection in the same format as the "plotselected"
  3741. event. If there's currently no selection, the function returns null.
  3742. */
  3743. (function ($) {
  3744. function init(plot) {
  3745. var selection = {
  3746. first: { x: -1, y: -1}, second: { x: -1, y: -1},
  3747. show: false,
  3748. active: false
  3749. };
  3750. // FIXME: The drag handling implemented here should be
  3751. // abstracted out, there's some similar code from a library in
  3752. // the navigation plugin, this should be massaged a bit to fit
  3753. // the Flot cases here better and reused. Doing this would
  3754. // make this plugin much slimmer.
  3755. var savedhandlers = {};
  3756. var mouseUpHandler = null;
  3757. function onMouseMove(e) {
  3758. if (selection.active) {
  3759. updateSelection(e);
  3760. plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
  3761. }
  3762. }
  3763. function onMouseDown(e) {
  3764. if (e.which != 1) // only accept left-click
  3765. return;
  3766. // cancel out any text selections
  3767. document.body.focus();
  3768. // prevent text selection and drag in old-school browsers
  3769. if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
  3770. savedhandlers.onselectstart = document.onselectstart;
  3771. document.onselectstart = function () { return false; };
  3772. }
  3773. if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
  3774. savedhandlers.ondrag = document.ondrag;
  3775. document.ondrag = function () { return false; };
  3776. }
  3777. setSelectionPos(selection.first, e);
  3778. selection.active = true;
  3779. // this is a bit silly, but we have to use a closure to be
  3780. // able to whack the same handler again
  3781. mouseUpHandler = function (e) { onMouseUp(e); };
  3782. $(document).one("mouseup", mouseUpHandler);
  3783. }
  3784. function onMouseUp(e) {
  3785. mouseUpHandler = null;
  3786. // revert drag stuff for old-school browsers
  3787. if (document.onselectstart !== undefined)
  3788. document.onselectstart = savedhandlers.onselectstart;
  3789. if (document.ondrag !== undefined)
  3790. document.ondrag = savedhandlers.ondrag;
  3791. // no more dragging
  3792. selection.active = false;
  3793. updateSelection(e);
  3794. if (selectionIsSane())
  3795. triggerSelectedEvent();
  3796. else {
  3797. // this counts as a clear
  3798. plot.getPlaceholder().trigger("plotunselected", [ ]);
  3799. plot.getPlaceholder().trigger("plotselecting", [ null ]);
  3800. }
  3801. return false;
  3802. }
  3803. function getSelection() {
  3804. if (!selectionIsSane())
  3805. return null;
  3806. if (!selection.show) return null;
  3807. var r = {}, c1 = selection.first, c2 = selection.second;
  3808. $.each(plot.getAxes(), function (name, axis) {
  3809. if (axis.used) {
  3810. var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
  3811. r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
  3812. }
  3813. });
  3814. return r;
  3815. }
  3816. function triggerSelectedEvent() {
  3817. var r = getSelection();
  3818. plot.getPlaceholder().trigger("plotselected", [ r ]);
  3819. // backwards-compat stuff, to be removed in future
  3820. if (r.xaxis && r.yaxis)
  3821. plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
  3822. }
  3823. function clamp(min, value, max) {
  3824. return value < min ? min: (value > max ? max: value);
  3825. }
  3826. function setSelectionPos(pos, e) {
  3827. var o = plot.getOptions();
  3828. var offset = plot.getPlaceholder().offset();
  3829. var plotOffset = plot.getPlotOffset();
  3830. pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
  3831. pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
  3832. if (o.selection.mode == "y")
  3833. pos.x = pos == selection.first ? 0 : plot.width();
  3834. if (o.selection.mode == "x")
  3835. pos.y = pos == selection.first ? 0 : plot.height();
  3836. }
  3837. function updateSelection(pos) {
  3838. if (pos.pageX == null)
  3839. return;
  3840. setSelectionPos(selection.second, pos);
  3841. if (selectionIsSane()) {
  3842. selection.show = true;
  3843. plot.triggerRedrawOverlay();
  3844. }
  3845. else
  3846. clearSelection(true);
  3847. }
  3848. function clearSelection(preventEvent) {
  3849. if (selection.show) {
  3850. selection.show = false;
  3851. plot.triggerRedrawOverlay();
  3852. if (!preventEvent)
  3853. plot.getPlaceholder().trigger("plotunselected", [ ]);
  3854. }
  3855. }
  3856. // function taken from markings support in Flot
  3857. function extractRange(ranges, coord) {
  3858. var axis, from, to, key, axes = plot.getAxes();
  3859. for (var k in axes) {
  3860. axis = axes[k];
  3861. if (axis.direction == coord) {
  3862. key = coord + axis.n + "axis";
  3863. if (!ranges[key] && axis.n == 1)
  3864. key = coord + "axis"; // support x1axis as xaxis
  3865. if (ranges[key]) {
  3866. from = ranges[key].from;
  3867. to = ranges[key].to;
  3868. break;
  3869. }
  3870. }
  3871. }
  3872. // backwards-compat stuff - to be removed in future
  3873. if (!ranges[key]) {
  3874. axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
  3875. from = ranges[coord + "1"];
  3876. to = ranges[coord + "2"];
  3877. }
  3878. // auto-reverse as an added bonus
  3879. if (from != null && to != null && from > to) {
  3880. var tmp = from;
  3881. from = to;
  3882. to = tmp;
  3883. }
  3884. return { from: from, to: to, axis: axis };
  3885. }
  3886. function setSelection(ranges, preventEvent) {
  3887. var axis, range, o = plot.getOptions();
  3888. if (o.selection.mode == "y") {
  3889. selection.first.x = 0;
  3890. selection.second.x = plot.width();
  3891. }
  3892. else {
  3893. range = extractRange(ranges, "x");
  3894. selection.first.x = range.axis.p2c(range.from);
  3895. selection.second.x = range.axis.p2c(range.to);
  3896. }
  3897. if (o.selection.mode == "x") {
  3898. selection.first.y = 0;
  3899. selection.second.y = plot.height();
  3900. }
  3901. else {
  3902. range = extractRange(ranges, "y");
  3903. selection.first.y = range.axis.p2c(range.from);
  3904. selection.second.y = range.axis.p2c(range.to);
  3905. }
  3906. selection.show = true;
  3907. plot.triggerRedrawOverlay();
  3908. if (!preventEvent && selectionIsSane())
  3909. triggerSelectedEvent();
  3910. }
  3911. function selectionIsSane() {
  3912. var minSize = plot.getOptions().selection.minSize;
  3913. return Math.abs(selection.second.x - selection.first.x) >= minSize &&
  3914. Math.abs(selection.second.y - selection.first.y) >= minSize;
  3915. }
  3916. plot.clearSelection = clearSelection;
  3917. plot.setSelection = setSelection;
  3918. plot.getSelection = getSelection;
  3919. plot.hooks.bindEvents.push(function(plot, eventHolder) {
  3920. var o = plot.getOptions();
  3921. if (o.selection.mode != null) {
  3922. eventHolder.mousemove(onMouseMove);
  3923. eventHolder.mousedown(onMouseDown);
  3924. }
  3925. });
  3926. plot.hooks.drawOverlay.push(function (plot, ctx) {
  3927. // draw selection
  3928. if (selection.show && selectionIsSane()) {
  3929. var plotOffset = plot.getPlotOffset();
  3930. var o = plot.getOptions();
  3931. ctx.save();
  3932. ctx.translate(plotOffset.left, plotOffset.top);
  3933. var c = $.color.parse(o.selection.color);
  3934. ctx.strokeStyle = c.scale('a', 0.8).toString();
  3935. ctx.lineWidth = 1;
  3936. ctx.lineJoin = o.selection.shape;
  3937. ctx.fillStyle = c.scale('a', 0.4).toString();
  3938. var x = Math.min(selection.first.x, selection.second.x) + 0.5,
  3939. y = Math.min(selection.first.y, selection.second.y) + 0.5,
  3940. w = Math.abs(selection.second.x - selection.first.x) - 1,
  3941. h = Math.abs(selection.second.y - selection.first.y) - 1;
  3942. ctx.fillRect(x, y, w, h);
  3943. ctx.strokeRect(x, y, w, h);
  3944. ctx.restore();
  3945. }
  3946. });
  3947. plot.hooks.shutdown.push(function (plot, eventHolder) {
  3948. eventHolder.unbind("mousemove", onMouseMove);
  3949. eventHolder.unbind("mousedown", onMouseDown);
  3950. if (mouseUpHandler)
  3951. $(document).unbind("mouseup", mouseUpHandler);
  3952. });
  3953. }
  3954. $.plot.plugins.push({
  3955. init: init,
  3956. options: {
  3957. selection: {
  3958. mode: null, // one of null, "x", "y" or "xy"
  3959. color: "#e8cfac",
  3960. shape: "round", // one of "round", "miter", or "bevel"
  3961. minSize: 5 // minimum number of pixels
  3962. }
  3963. },
  3964. name: 'selection',
  3965. version: '1.1'
  3966. });
  3967. })(jQuery);
  3968. /* Flot plugin for stacking data sets rather than overlyaing them.
  3969. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3970. Licensed under the MIT license.
  3971. The plugin assumes the data is sorted on x (or y if stacking horizontally).
  3972. For line charts, it is assumed that if a line has an undefined gap (from a
  3973. null point), then the line above it should have the same gap - insert zeros
  3974. instead of "null" if you want another behaviour. This also holds for the start
  3975. and end of the chart. Note that stacking a mix of positive and negative values
  3976. in most instances doesn't make sense (so it looks weird).
  3977. Two or more series are stacked when their "stack" attribute is set to the same
  3978. key (which can be any number or string or just "true"). To specify the default
  3979. stack, you can set the stack option like this:
  3980. series: {
  3981. stack: null/false, true, or a key (number/string)
  3982. }
  3983. You can also specify it for a single series, like this:
  3984. $.plot( $("#placeholder"), [{
  3985. data: [ ... ],
  3986. stack: true
  3987. }])
  3988. The stacking order is determined by the order of the data series in the array
  3989. (later series end up on top of the previous).
  3990. Internally, the plugin modifies the datapoints in each series, adding an
  3991. offset to the y value. For line series, extra data points are inserted through
  3992. interpolation. If there's a second y value, it's also adjusted (e.g for bar
  3993. charts or filled areas).
  3994. */
  3995. (function ($) {
  3996. var options = {
  3997. series: { stack: null } // or number/string
  3998. };
  3999. function init(plot) {
  4000. function findMatchingSeries(s, allseries) {
  4001. var res = null;
  4002. for (var i = 0; i < allseries.length; ++i) {
  4003. if (s == allseries[i])
  4004. break;
  4005. if (allseries[i].stack == s.stack)
  4006. res = allseries[i];
  4007. }
  4008. return res;
  4009. }
  4010. function stackData(plot, s, datapoints) {
  4011. if (s.stack == null || s.stack === false)
  4012. return;
  4013. var other = findMatchingSeries(s, plot.getData());
  4014. if (!other)
  4015. return;
  4016. var ps = datapoints.pointsize,
  4017. points = datapoints.points,
  4018. otherps = other.datapoints.pointsize,
  4019. otherpoints = other.datapoints.points,
  4020. newpoints = [],
  4021. px, py, intery, qx, qy, bottom,
  4022. withlines = s.lines.show,
  4023. horizontal = s.bars.horizontal,
  4024. withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y),
  4025. withsteps = withlines && s.lines.steps,
  4026. fromgap = true,
  4027. keyOffset = horizontal ? 1 : 0,
  4028. accumulateOffset = horizontal ? 0 : 1,
  4029. i = 0, j = 0, l, m;
  4030. while (true) {
  4031. if (i >= points.length)
  4032. break;
  4033. l = newpoints.length;
  4034. if (points[i] == null) {
  4035. // copy gaps
  4036. for (m = 0; m < ps; ++m)
  4037. newpoints.push(points[i + m]);
  4038. i += ps;
  4039. }
  4040. else if (j >= otherpoints.length) {
  4041. // for lines, we can't use the rest of the points
  4042. if (!withlines) {
  4043. for (m = 0; m < ps; ++m)
  4044. newpoints.push(points[i + m]);
  4045. }
  4046. i += ps;
  4047. }
  4048. else if (otherpoints[j] == null) {
  4049. // oops, got a gap
  4050. for (m = 0; m < ps; ++m)
  4051. newpoints.push(null);
  4052. fromgap = true;
  4053. j += otherps;
  4054. }
  4055. else {
  4056. // cases where we actually got two points
  4057. px = points[i + keyOffset];
  4058. py = points[i + accumulateOffset];
  4059. qx = otherpoints[j + keyOffset];
  4060. qy = otherpoints[j + accumulateOffset];
  4061. bottom = 0;
  4062. if (px == qx) {
  4063. for (m = 0; m < ps; ++m)
  4064. newpoints.push(points[i + m]);
  4065. newpoints[l + accumulateOffset] += qy;
  4066. bottom = qy;
  4067. i += ps;
  4068. j += otherps;
  4069. }
  4070. else if (px > qx) {
  4071. // we got past point below, might need to
  4072. // insert interpolated extra point
  4073. if (withlines && i > 0 && points[i - ps] != null) {
  4074. intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px);
  4075. newpoints.push(qx);
  4076. newpoints.push(intery + qy);
  4077. for (m = 2; m < ps; ++m)
  4078. newpoints.push(points[i + m]);
  4079. bottom = qy;
  4080. }
  4081. j += otherps;
  4082. }
  4083. else { // px < qx
  4084. if (fromgap && withlines) {
  4085. // if we come from a gap, we just skip this point
  4086. i += ps;
  4087. continue;
  4088. }
  4089. for (m = 0; m < ps; ++m)
  4090. newpoints.push(points[i + m]);
  4091. // we might be able to interpolate a point below,
  4092. // this can give us a better y
  4093. if (withlines && j > 0 && otherpoints[j - otherps] != null)
  4094. bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx);
  4095. newpoints[l + accumulateOffset] += bottom;
  4096. i += ps;
  4097. }
  4098. fromgap = false;
  4099. if (l != newpoints.length && withbottom)
  4100. newpoints[l + 2] += bottom;
  4101. }
  4102. // maintain the line steps invariant
  4103. if (withsteps && l != newpoints.length && l > 0
  4104. && newpoints[l] != null
  4105. && newpoints[l] != newpoints[l - ps]
  4106. && newpoints[l + 1] != newpoints[l - ps + 1]) {
  4107. for (m = 0; m < ps; ++m)
  4108. newpoints[l + ps + m] = newpoints[l + m];
  4109. newpoints[l + 1] = newpoints[l - ps + 1];
  4110. }
  4111. }
  4112. datapoints.points = newpoints;
  4113. }
  4114. plot.hooks.processDatapoints.push(stackData);
  4115. }
  4116. $.plot.plugins.push({
  4117. init: init,
  4118. options: options,
  4119. name: 'stack',
  4120. version: '1.2'
  4121. });
  4122. })(jQuery);
  4123. /* Flot plugin for showing crosshairs when the mouse hovers over the plot.
  4124. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  4125. Licensed under the MIT license.
  4126. The plugin supports these options:
  4127. crosshair: {
  4128. mode: null or "x" or "y" or "xy"
  4129. color: color
  4130. lineWidth: number
  4131. }
  4132. Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
  4133. crosshair that lets you trace the values on the x axis, "y" enables a
  4134. horizontal crosshair and "xy" enables them both. "color" is the color of the
  4135. crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
  4136. the drawn lines (default is 1).
  4137. The plugin also adds four public methods:
  4138. - setCrosshair( pos )
  4139. Set the position of the crosshair. Note that this is cleared if the user
  4140. moves the mouse. "pos" is in coordinates of the plot and should be on the
  4141. form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
  4142. axes), which is coincidentally the same format as what you get from a
  4143. "plothover" event. If "pos" is null, the crosshair is cleared.
  4144. - clearCrosshair()
  4145. Clear the crosshair.
  4146. - lockCrosshair(pos)
  4147. Cause the crosshair to lock to the current location, no longer updating if
  4148. the user moves the mouse. Optionally supply a position (passed on to
  4149. setCrosshair()) to move it to.
  4150. Example usage:
  4151. var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
  4152. $("#graph").bind( "plothover", function ( evt, position, item ) {
  4153. if ( item ) {
  4154. // Lock the crosshair to the data point being hovered
  4155. myFlot.lockCrosshair({
  4156. x: item.datapoint[ 0 ],
  4157. y: item.datapoint[ 1 ]
  4158. });
  4159. } else {
  4160. // Return normal crosshair operation
  4161. myFlot.unlockCrosshair();
  4162. }
  4163. });
  4164. - unlockCrosshair()
  4165. Free the crosshair to move again after locking it.
  4166. */
  4167. (function ($) {
  4168. var options = {
  4169. crosshair: {
  4170. mode: null, // one of null, "x", "y" or "xy",
  4171. color: "rgba(170, 0, 0, 0.80)",
  4172. lineWidth: 1
  4173. }
  4174. };
  4175. function init(plot) {
  4176. // position of crosshair in pixels
  4177. var crosshair = { x: -1, y: -1, locked: false };
  4178. plot.setCrosshair = function setCrosshair(pos) {
  4179. if (!pos)
  4180. crosshair.x = -1;
  4181. else {
  4182. var o = plot.p2c(pos);
  4183. crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
  4184. crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
  4185. }
  4186. plot.triggerRedrawOverlay();
  4187. };
  4188. plot.clearCrosshair = plot.setCrosshair; // passes null for pos
  4189. plot.lockCrosshair = function lockCrosshair(pos) {
  4190. if (pos)
  4191. plot.setCrosshair(pos);
  4192. crosshair.locked = true;
  4193. };
  4194. plot.unlockCrosshair = function unlockCrosshair() {
  4195. crosshair.locked = false;
  4196. };
  4197. function onMouseOut(e) {
  4198. if (crosshair.locked)
  4199. return;
  4200. if (crosshair.x != -1) {
  4201. crosshair.x = -1;
  4202. plot.triggerRedrawOverlay();
  4203. }
  4204. }
  4205. function onMouseMove(e) {
  4206. if (crosshair.locked)
  4207. return;
  4208. if (plot.getSelection && plot.getSelection()) {
  4209. crosshair.x = -1; // hide the crosshair while selecting
  4210. return;
  4211. }
  4212. var offset = plot.offset();
  4213. crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
  4214. crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
  4215. plot.triggerRedrawOverlay();
  4216. }
  4217. plot.hooks.bindEvents.push(function (plot, eventHolder) {
  4218. if (!plot.getOptions().crosshair.mode)
  4219. return;
  4220. eventHolder.mouseout(onMouseOut);
  4221. eventHolder.mousemove(onMouseMove);
  4222. });
  4223. plot.hooks.drawOverlay.push(function (plot, ctx) {
  4224. var c = plot.getOptions().crosshair;
  4225. if (!c.mode)
  4226. return;
  4227. var plotOffset = plot.getPlotOffset();
  4228. ctx.save();
  4229. ctx.translate(plotOffset.left, plotOffset.top);
  4230. if (crosshair.x != -1) {
  4231. var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
  4232. ctx.strokeStyle = c.color;
  4233. ctx.lineWidth = c.lineWidth;
  4234. ctx.lineJoin = "round";
  4235. ctx.beginPath();
  4236. if (c.mode.indexOf("x") != -1) {
  4237. var drawX = Math.floor(crosshair.x) + adj;
  4238. ctx.moveTo(drawX, 0);
  4239. ctx.lineTo(drawX, plot.height());
  4240. }
  4241. if (c.mode.indexOf("y") != -1) {
  4242. var drawY = Math.floor(crosshair.y) + adj;
  4243. ctx.moveTo(0, drawY);
  4244. ctx.lineTo(plot.width(), drawY);
  4245. }
  4246. ctx.stroke();
  4247. }
  4248. ctx.restore();
  4249. });
  4250. plot.hooks.shutdown.push(function (plot, eventHolder) {
  4251. eventHolder.unbind("mouseout", onMouseOut);
  4252. eventHolder.unbind("mousemove", onMouseMove);
  4253. });
  4254. }
  4255. $.plot.plugins.push({
  4256. init: init,
  4257. options: options,
  4258. name: 'crosshair',
  4259. version: '1.0'
  4260. });
  4261. })(jQuery);
  4262. /*
  4263. * jquery.flot.tooltip
  4264. *
  4265. * description: easy-to-use tooltips for Flot charts
  4266. * version: 0.9.0
  4267. * authors: Krzysztof Urbas @krzysu [myviews.pl],Evan Steinkerchner @Roundaround
  4268. * website: https://github.com/krzysu/flot.tooltip
  4269. *
  4270. * build on 2016-07-26
  4271. * released under MIT License, 2012
  4272. */
  4273. !function(a){var b={tooltip:{show:!1,cssClass:"flotTip",content:"%s | X: %x | Y: %y",xDateFormat:null,yDateFormat:null,monthNames:null,dayNames:null,shifts:{x:10,y:20},defaultTheme:!0,snap:!0,lines:!1,clickTips:!1,onHover:function(a,b){},$compat:!1}};b.tooltipOpts=b.tooltip;var c=function(a){this.tipPosition={x:0,y:0},this.init(a)};c.prototype.init=function(b){function c(a){var c={};c.x=a.pageX,c.y=a.pageY,b.setTooltipPosition(c)}function d(c,d,g){f.clickmode?(a(b.getPlaceholder()).bind("plothover",e),b.hideTooltip(),f.clickmode=!1):(e(c,d,g),f.getDomElement().is(":visible")&&(a(b.getPlaceholder()).unbind("plothover",e),f.clickmode=!0))}function e(c,d,e){var g=function(a,b,c,d){return Math.sqrt((c-a)*(c-a)+(d-b)*(d-b))},h=function(a,b,c,d,e,f,h){if(!h||(h=function(a,b,c,d,e,f){if("undefined"!=typeof c)return{x:c,y:b};if("undefined"!=typeof d)return{x:a,y:d};var g,h=-1/((f-d)/(e-c));return{x:g=(e*(a*h-b+d)+c*(a*-h+b-f))/(h*(e-c)+d-f),y:h*g-h*a+b}}(a,b,c,d,e,f),h.x>=Math.min(c,e)&&h.x<=Math.max(c,e)&&h.y>=Math.min(d,f)&&h.y<=Math.max(d,f))){var i=d-f,j=e-c,k=c*f-d*e;return Math.abs(i*a+j*b+k)/Math.sqrt(i*i+j*j)}var l=g(a,b,c,d),m=g(a,b,e,f);return l>m?m:l};if(e)b.showTooltip(e,f.tooltipOptions.snap?e:d);else if(f.plotOptions.series.lines.show&&f.tooltipOptions.lines===!0){var i=f.plotOptions.grid.mouseActiveRadius,j={distance:i+1},k=d;a.each(b.getData(),function(a,c){for(var e=0,i=-1,l=1;l<c.data.length;l++)c.data[l-1][0]<=d.x&&c.data[l][0]>=d.x&&(e=l-1,i=l);if(-1===i)return void b.hideTooltip();var m={x:c.data[e][0],y:c.data[e][1]},n={x:c.data[i][0],y:c.data[i][1]},o=h(c.xaxis.p2c(d.x),c.yaxis.p2c(d.y),c.xaxis.p2c(m.x),c.yaxis.p2c(m.y),c.xaxis.p2c(n.x),c.yaxis.p2c(n.y),!1);if(o<j.distance){var p=g(m.x,m.y,d.x,d.y)<g(d.x,d.y,n.x,n.y)?e:i,q=(c.datapoints.pointsize,[d.x,m.y+(n.y-m.y)*((d.x-m.x)/(n.x-m.x))]),r={datapoint:q,dataIndex:p,series:c,seriesIndex:a};j={distance:o,item:r},f.tooltipOptions.snap&&(k={pageX:c.xaxis.p2c(q[0]),pageY:c.yaxis.p2c(q[1])})}}),j.distance<i+1?b.showTooltip(j.item,k):b.hideTooltip()}else b.hideTooltip()}var f=this,g=a.plot.plugins.length;if(this.plotPlugins=[],g)for(var h=0;g>h;h++)this.plotPlugins.push(a.plot.plugins[h].name);b.hooks.bindEvents.push(function(b,g){if(f.plotOptions=b.getOptions(),"boolean"==typeof f.plotOptions.tooltip&&(f.plotOptions.tooltipOpts.show=f.plotOptions.tooltip,f.plotOptions.tooltip=f.plotOptions.tooltipOpts,delete f.plotOptions.tooltipOpts),f.plotOptions.tooltip.show!==!1&&"undefined"!=typeof f.plotOptions.tooltip.show){f.tooltipOptions=f.plotOptions.tooltip,f.tooltipOptions.$compat?(f.wfunc="width",f.hfunc="height"):(f.wfunc="innerWidth",f.hfunc="innerHeight");f.getDomElement();a(b.getPlaceholder()).bind("plothover",e),f.tooltipOptions.clickTips&&a(b.getPlaceholder()).bind("plotclick",d),f.clickmode=!1,a(g).bind("mousemove",c)}}),b.hooks.shutdown.push(function(b,f){a(b.getPlaceholder()).unbind("plothover",e),a(b.getPlaceholder()).unbind("plotclick",d),b.removeTooltip(),a(f).unbind("mousemove",c)}),b.setTooltipPosition=function(b){var c=f.getDomElement(),d=c.outerWidth()+f.tooltipOptions.shifts.x,e=c.outerHeight()+f.tooltipOptions.shifts.y;b.x-a(window).scrollLeft()>a(window)[f.wfunc]()-d&&(b.x-=d,b.x=Math.max(b.x,0)),b.y-a(window).scrollTop()>a(window)[f.hfunc]()-e&&(b.y-=e),isNaN(b.x)?f.tipPosition.x=f.tipPosition.xPrev:(f.tipPosition.x=b.x,f.tipPosition.xPrev=b.x),isNaN(b.y)?f.tipPosition.y=f.tipPosition.yPrev:(f.tipPosition.y=b.y,f.tipPosition.yPrev=b.y)},b.showTooltip=function(a,c,d){var e=f.getDomElement(),g=f.stringFormat(f.tooltipOptions.content,a);""!==g&&(e.html(g),b.setTooltipPosition({x:f.tipPosition.x,y:f.tipPosition.y}),e.css({left:f.tipPosition.x+f.tooltipOptions.shifts.x,top:f.tipPosition.y+f.tooltipOptions.shifts.y}).show(),"function"==typeof f.tooltipOptions.onHover&&f.tooltipOptions.onHover(a,e))},b.hideTooltip=function(){f.getDomElement().hide().html("")},b.removeTooltip=function(){f.getDomElement().remove()}},c.prototype.getDomElement=function(){var b=a("<div>");return this.tooltipOptions&&this.tooltipOptions.cssClass&&(b=a("."+this.tooltipOptions.cssClass),0===b.length&&(b=a("<div />").addClass(this.tooltipOptions.cssClass),b.appendTo("body").hide().css({position:"absolute"}),this.tooltipOptions.defaultTheme&&b.css({background:"#fff","z-index":"1040",padding:"0.4em 0.6em","border-radius":"0.5em","font-size":"0.8em",border:"1px solid #111",display:"none","white-space":"nowrap"}))),b},c.prototype.stringFormat=function(a,b){var c,d,e,f,g,h=/%p\.{0,1}(\d{0,})/,i=/%s/,j=/%c/,k=/%lx/,l=/%ly/,m=/%x\.{0,1}(\d{0,})/,n=/%y\.{0,1}(\d{0,})/,o="%x",p="%y",q="%ct",r="%n";if("undefined"!=typeof b.series.threshold?(c=b.datapoint[0],d=b.datapoint[1],e=b.datapoint[2]):"undefined"!=typeof b.series.curvedLines?(c=b.datapoint[0],d=b.datapoint[1]):"undefined"!=typeof b.series.lines&&b.series.lines.steps?(c=b.series.datapoints.points[2*b.dataIndex],d=b.series.datapoints.points[2*b.dataIndex+1],e=""):(c=b.series.data[b.dataIndex][0],d=b.series.data[b.dataIndex][1],e=b.series.data[b.dataIndex][2]),null===b.series.label&&b.series.originSeries&&(b.series.label=b.series.originSeries.label),"function"==typeof a&&(a=a(b.series.label,c,d,b)),"boolean"==typeof a&&!a)return"";if(e&&(a=a.replace(q,e)),"undefined"!=typeof b.series.percent?f=b.series.percent:"undefined"!=typeof b.series.percents&&(f=b.series.percents[b.dataIndex]),"number"==typeof f&&(a=this.adjustValPrecision(h,a,f)),b.series.hasOwnProperty("pie")&&"undefined"!=typeof b.series.data[0][1]&&(g=b.series.data[0][1]),"number"==typeof g&&(a=a.replace(r,g)),a="undefined"!=typeof b.series.label?a.replace(i,b.series.label):a.replace(i,""),a="undefined"!=typeof b.series.color?a.replace(j,b.series.color):a.replace(j,""),a=this.hasAxisLabel("xaxis",b)?a.replace(k,b.series.xaxis.options.axisLabel):a.replace(k,""),a=this.hasAxisLabel("yaxis",b)?a.replace(l,b.series.yaxis.options.axisLabel):a.replace(l,""),this.isTimeMode("xaxis",b)&&this.isXDateFormat(b)&&(a=a.replace(m,this.timestampToDate(c,this.tooltipOptions.xDateFormat,b.series.xaxis.options))),this.isTimeMode("yaxis",b)&&this.isYDateFormat(b)&&(a=a.replace(n,this.timestampToDate(d,this.tooltipOptions.yDateFormat,b.series.yaxis.options))),"number"==typeof c&&(a=this.adjustValPrecision(m,a,c)),"number"==typeof d&&(a=this.adjustValPrecision(n,a,d)),"undefined"!=typeof b.series.xaxis.ticks){var s;s=this.hasRotatedXAxisTicks(b)?"rotatedTicks":"ticks";var t=b.dataIndex+b.seriesIndex;for(var u in b.series.xaxis[s])if(b.series.xaxis[s].hasOwnProperty(t)&&!this.isTimeMode("xaxis",b)){var v=this.isCategoriesMode("xaxis",b)?b.series.xaxis[s][t].label:b.series.xaxis[s][t].v;v===c&&(a=a.replace(m,b.series.xaxis[s][t].label.replace(/\$/g,"$$$$")))}}if("undefined"!=typeof b.series.yaxis.ticks)for(var w in b.series.yaxis.ticks)if(b.series.yaxis.ticks.hasOwnProperty(w)){var x=this.isCategoriesMode("yaxis",b)?b.series.yaxis.ticks[w].label:b.series.yaxis.ticks[w].v;x===d&&(a=a.replace(n,b.series.yaxis.ticks[w].label.replace(/\$/g,"$$$$")))}return"undefined"!=typeof b.series.xaxis.tickFormatter&&(a=a.replace(o,b.series.xaxis.tickFormatter(c,b.series.xaxis).replace(/\$/g,"$$"))),"undefined"!=typeof b.series.yaxis.tickFormatter&&(a=a.replace(p,b.series.yaxis.tickFormatter(d,b.series.yaxis).replace(/\$/g,"$$"))),a},c.prototype.isTimeMode=function(a,b){return"undefined"!=typeof b.series[a].options.mode&&"time"===b.series[a].options.mode},c.prototype.isXDateFormat=function(a){return"undefined"!=typeof this.tooltipOptions.xDateFormat&&null!==this.tooltipOptions.xDateFormat},c.prototype.isYDateFormat=function(a){return"undefined"!=typeof this.tooltipOptions.yDateFormat&&null!==this.tooltipOptions.yDateFormat},c.prototype.isCategoriesMode=function(a,b){return"undefined"!=typeof b.series[a].options.mode&&"categories"===b.series[a].options.mode},c.prototype.timestampToDate=function(b,c,d){var e=a.plot.dateGenerator(b,d);return a.plot.formatDate(e,c,this.tooltipOptions.monthNames,this.tooltipOptions.dayNames)},c.prototype.adjustValPrecision=function(a,b,c){var d,e=b.match(a);return null!==e&&""!==RegExp.$1&&(d=RegExp.$1,c=c.toFixed(d),b=b.replace(a,c)),b},c.prototype.hasAxisLabel=function(b,c){return-1!==a.inArray("axisLabels",this.plotPlugins)&&"undefined"!=typeof c.series[b].options.axisLabel&&c.series[b].options.axisLabel.length>0},c.prototype.hasRotatedXAxisTicks=function(b){return-1!==a.inArray("tickRotor",this.plotPlugins)&&"undefined"!=typeof b.series.xaxis.rotatedTicks};var d=function(a){new c(a)};a.plot.plugins.push({init:d,options:b,name:"tooltip",version:"0.8.5"})}(jQuery);