chartist.js 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488
  1. (function (root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD. Register as an anonymous module unless amdModuleId is set
  4. define('Chartist', [], function () {
  5. return (root['Chartist'] = factory());
  6. });
  7. } else if (typeof module === 'object' && module.exports) {
  8. // Node. Does not work with strict CommonJS, but
  9. // only CommonJS-like environments that support module.exports,
  10. // like Node.
  11. module.exports = factory();
  12. } else {
  13. root['Chartist'] = factory();
  14. }
  15. }(this, function () {
  16. /* Chartist.js 0.11.0
  17. * Copyright © 2017 Gion Kunz
  18. * Free to use under either the WTFPL license or the MIT license.
  19. * https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-WTFPL
  20. * https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-MIT
  21. */
  22. /**
  23. * The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
  24. *
  25. * @module Chartist.Core
  26. */
  27. var Chartist = {
  28. version: '0.11.0'
  29. };
  30. (function (window, document, Chartist) {
  31. 'use strict';
  32. /**
  33. * This object contains all namespaces used within Chartist.
  34. *
  35. * @memberof Chartist.Core
  36. * @type {{svg: string, xmlns: string, xhtml: string, xlink: string, ct: string}}
  37. */
  38. Chartist.namespaces = {
  39. svg: 'http://www.w3.org/2000/svg',
  40. xmlns: 'http://www.w3.org/2000/xmlns/',
  41. xhtml: 'http://www.w3.org/1999/xhtml',
  42. xlink: 'http://www.w3.org/1999/xlink',
  43. ct: 'http://gionkunz.github.com/chartist-js/ct'
  44. };
  45. /**
  46. * Helps to simplify functional style code
  47. *
  48. * @memberof Chartist.Core
  49. * @param {*} n This exact value will be returned by the noop function
  50. * @return {*} The same value that was provided to the n parameter
  51. */
  52. Chartist.noop = function (n) {
  53. return n;
  54. };
  55. /**
  56. * Generates a-z from a number 0 to 26
  57. *
  58. * @memberof Chartist.Core
  59. * @param {Number} n A number from 0 to 26 that will result in a letter a-z
  60. * @return {String} A character from a-z based on the input number n
  61. */
  62. Chartist.alphaNumerate = function (n) {
  63. // Limit to a-z
  64. return String.fromCharCode(97 + n % 26);
  65. };
  66. /**
  67. * Simple recursive object extend
  68. *
  69. * @memberof Chartist.Core
  70. * @param {Object} target Target object where the source will be merged into
  71. * @param {Object...} sources This object (objects) will be merged into target and then target is returned
  72. * @return {Object} An object that has the same reference as target but is extended and merged with the properties of source
  73. */
  74. Chartist.extend = function (target) {
  75. var i, source, sourceProp;
  76. target = target || {};
  77. for (i = 1; i < arguments.length; i++) {
  78. source = arguments[i];
  79. for (var prop in source) {
  80. sourceProp = source[prop];
  81. if (typeof sourceProp === 'object' && sourceProp !== null && !(sourceProp instanceof Array)) {
  82. target[prop] = Chartist.extend(target[prop], sourceProp);
  83. } else {
  84. target[prop] = sourceProp;
  85. }
  86. }
  87. }
  88. return target;
  89. };
  90. /**
  91. * Replaces all occurrences of subStr in str with newSubStr and returns a new string.
  92. *
  93. * @memberof Chartist.Core
  94. * @param {String} str
  95. * @param {String} subStr
  96. * @param {String} newSubStr
  97. * @return {String}
  98. */
  99. Chartist.replaceAll = function(str, subStr, newSubStr) {
  100. return str.replace(new RegExp(subStr, 'g'), newSubStr);
  101. };
  102. /**
  103. * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.
  104. *
  105. * @memberof Chartist.Core
  106. * @param {Number} value
  107. * @param {String} unit
  108. * @return {String} Returns the passed number value with unit.
  109. */
  110. Chartist.ensureUnit = function(value, unit) {
  111. if(typeof value === 'number') {
  112. value = value + unit;
  113. }
  114. return value;
  115. };
  116. /**
  117. * Converts a number or string to a quantity object.
  118. *
  119. * @memberof Chartist.Core
  120. * @param {String|Number} input
  121. * @return {Object} Returns an object containing the value as number and the unit as string.
  122. */
  123. Chartist.quantity = function(input) {
  124. if (typeof input === 'string') {
  125. var match = (/^(\d+)\s*(.*)$/g).exec(input);
  126. return {
  127. value : +match[1],
  128. unit: match[2] || undefined
  129. };
  130. }
  131. return { value: input };
  132. };
  133. /**
  134. * This is a wrapper around document.querySelector that will return the query if it's already of type Node
  135. *
  136. * @memberof Chartist.Core
  137. * @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly
  138. * @return {Node}
  139. */
  140. Chartist.querySelector = function(query) {
  141. return query instanceof Node ? query : document.querySelector(query);
  142. };
  143. /**
  144. * Functional style helper to produce array with given length initialized with undefined values
  145. *
  146. * @memberof Chartist.Core
  147. * @param length
  148. * @return {Array}
  149. */
  150. Chartist.times = function(length) {
  151. return Array.apply(null, new Array(length));
  152. };
  153. /**
  154. * Sum helper to be used in reduce functions
  155. *
  156. * @memberof Chartist.Core
  157. * @param previous
  158. * @param current
  159. * @return {*}
  160. */
  161. Chartist.sum = function(previous, current) {
  162. return previous + (current ? current : 0);
  163. };
  164. /**
  165. * Multiply helper to be used in `Array.map` for multiplying each value of an array with a factor.
  166. *
  167. * @memberof Chartist.Core
  168. * @param {Number} factor
  169. * @returns {Function} Function that can be used in `Array.map` to multiply each value in an array
  170. */
  171. Chartist.mapMultiply = function(factor) {
  172. return function(num) {
  173. return num * factor;
  174. };
  175. };
  176. /**
  177. * Add helper to be used in `Array.map` for adding a addend to each value of an array.
  178. *
  179. * @memberof Chartist.Core
  180. * @param {Number} addend
  181. * @returns {Function} Function that can be used in `Array.map` to add a addend to each value in an array
  182. */
  183. Chartist.mapAdd = function(addend) {
  184. return function(num) {
  185. return num + addend;
  186. };
  187. };
  188. /**
  189. * Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).
  190. *
  191. * @memberof Chartist.Core
  192. * @param arr
  193. * @param cb
  194. * @return {Array}
  195. */
  196. Chartist.serialMap = function(arr, cb) {
  197. var result = [],
  198. length = Math.max.apply(null, arr.map(function(e) {
  199. return e.length;
  200. }));
  201. Chartist.times(length).forEach(function(e, index) {
  202. var args = arr.map(function(e) {
  203. return e[index];
  204. });
  205. result[index] = cb.apply(null, args);
  206. });
  207. return result;
  208. };
  209. /**
  210. * This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit.
  211. *
  212. * @memberof Chartist.Core
  213. * @param {Number} value The value that should be rounded with precision
  214. * @param {Number} [digits] The number of digits after decimal used to do the rounding
  215. * @returns {number} Rounded value
  216. */
  217. Chartist.roundWithPrecision = function(value, digits) {
  218. var precision = Math.pow(10, digits || Chartist.precision);
  219. return Math.round(value * precision) / precision;
  220. };
  221. /**
  222. * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.
  223. *
  224. * @memberof Chartist.Core
  225. * @type {number}
  226. */
  227. Chartist.precision = 8;
  228. /**
  229. * A map with characters to escape for strings to be safely used as attribute values.
  230. *
  231. * @memberof Chartist.Core
  232. * @type {Object}
  233. */
  234. Chartist.escapingMap = {
  235. '&': '&amp;',
  236. '<': '&lt;',
  237. '>': '&gt;',
  238. '"': '&quot;',
  239. '\'': '&#039;'
  240. };
  241. /**
  242. * This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.
  243. * If called with null or undefined the function will return immediately with null or undefined.
  244. *
  245. * @memberof Chartist.Core
  246. * @param {Number|String|Object} data
  247. * @return {String}
  248. */
  249. Chartist.serialize = function(data) {
  250. if(data === null || data === undefined) {
  251. return data;
  252. } else if(typeof data === 'number') {
  253. data = ''+data;
  254. } else if(typeof data === 'object') {
  255. data = JSON.stringify({data: data});
  256. }
  257. return Object.keys(Chartist.escapingMap).reduce(function(result, key) {
  258. return Chartist.replaceAll(result, key, Chartist.escapingMap[key]);
  259. }, data);
  260. };
  261. /**
  262. * This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.
  263. *
  264. * @memberof Chartist.Core
  265. * @param {String} data
  266. * @return {String|Number|Object}
  267. */
  268. Chartist.deserialize = function(data) {
  269. if(typeof data !== 'string') {
  270. return data;
  271. }
  272. data = Object.keys(Chartist.escapingMap).reduce(function(result, key) {
  273. return Chartist.replaceAll(result, Chartist.escapingMap[key], key);
  274. }, data);
  275. try {
  276. data = JSON.parse(data);
  277. data = data.data !== undefined ? data.data : data;
  278. } catch(e) {}
  279. return data;
  280. };
  281. /**
  282. * Create or reinitialize the SVG element for the chart
  283. *
  284. * @memberof Chartist.Core
  285. * @param {Node} container The containing DOM Node object that will be used to plant the SVG element
  286. * @param {String} width Set the width of the SVG element. Default is 100%
  287. * @param {String} height Set the height of the SVG element. Default is 100%
  288. * @param {String} className Specify a class to be added to the SVG element
  289. * @return {Object} The created/reinitialized SVG element
  290. */
  291. Chartist.createSvg = function (container, width, height, className) {
  292. var svg;
  293. width = width || '100%';
  294. height = height || '100%';
  295. // Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it
  296. // Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/
  297. Array.prototype.slice.call(container.querySelectorAll('svg')).filter(function filterChartistSvgObjects(svg) {
  298. return svg.getAttributeNS(Chartist.namespaces.xmlns, 'ct');
  299. }).forEach(function removePreviousElement(svg) {
  300. container.removeChild(svg);
  301. });
  302. // Create svg object with width and height or use 100% as default
  303. svg = new Chartist.Svg('svg').attr({
  304. width: width,
  305. height: height
  306. }).addClass(className);
  307. svg._node.style.width = width;
  308. svg._node.style.height = height;
  309. // Add the DOM node to our container
  310. container.appendChild(svg._node);
  311. return svg;
  312. };
  313. /**
  314. * Ensures that the data object passed as second argument to the charts is present and correctly initialized.
  315. *
  316. * @param {Object} data The data object that is passed as second argument to the charts
  317. * @return {Object} The normalized data object
  318. */
  319. Chartist.normalizeData = function(data, reverse, multi) {
  320. var labelCount;
  321. var output = {
  322. raw: data,
  323. normalized: {}
  324. };
  325. // Check if we should generate some labels based on existing series data
  326. output.normalized.series = Chartist.getDataArray({
  327. series: data.series || []
  328. }, reverse, multi);
  329. // If all elements of the normalized data array are arrays we're dealing with
  330. // multi series data and we need to find the largest series if they are un-even
  331. if (output.normalized.series.every(function(value) {
  332. return value instanceof Array;
  333. })) {
  334. // Getting the series with the the most elements
  335. labelCount = Math.max.apply(null, output.normalized.series.map(function(series) {
  336. return series.length;
  337. }));
  338. } else {
  339. // We're dealing with Pie data so we just take the normalized array length
  340. labelCount = output.normalized.series.length;
  341. }
  342. output.normalized.labels = (data.labels || []).slice();
  343. // Padding the labels to labelCount with empty strings
  344. Array.prototype.push.apply(
  345. output.normalized.labels,
  346. Chartist.times(Math.max(0, labelCount - output.normalized.labels.length)).map(function() {
  347. return '';
  348. })
  349. );
  350. if(reverse) {
  351. Chartist.reverseData(output.normalized);
  352. }
  353. return output;
  354. };
  355. /**
  356. * This function safely checks if an objects has an owned property.
  357. *
  358. * @param {Object} object The object where to check for a property
  359. * @param {string} property The property name
  360. * @returns {boolean} Returns true if the object owns the specified property
  361. */
  362. Chartist.safeHasProperty = function(object, property) {
  363. return object !== null &&
  364. typeof object === 'object' &&
  365. object.hasOwnProperty(property);
  366. };
  367. /**
  368. * Checks if a value is considered a hole in the data series.
  369. *
  370. * @param {*} value
  371. * @returns {boolean} True if the value is considered a data hole
  372. */
  373. Chartist.isDataHoleValue = function(value) {
  374. return value === null ||
  375. value === undefined ||
  376. (typeof value === 'number' && isNaN(value));
  377. };
  378. /**
  379. * Reverses the series, labels and series data arrays.
  380. *
  381. * @memberof Chartist.Core
  382. * @param data
  383. */
  384. Chartist.reverseData = function(data) {
  385. data.labels.reverse();
  386. data.series.reverse();
  387. for (var i = 0; i < data.series.length; i++) {
  388. if(typeof(data.series[i]) === 'object' && data.series[i].data !== undefined) {
  389. data.series[i].data.reverse();
  390. } else if(data.series[i] instanceof Array) {
  391. data.series[i].reverse();
  392. }
  393. }
  394. };
  395. /**
  396. * Convert data series into plain array
  397. *
  398. * @memberof Chartist.Core
  399. * @param {Object} data The series object that contains the data to be visualized in the chart
  400. * @param {Boolean} [reverse] If true the whole data is reversed by the getDataArray call. This will modify the data object passed as first parameter. The labels as well as the series order is reversed. The whole series data arrays are reversed too.
  401. * @param {Boolean} [multi] Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created.
  402. * @return {Array} A plain array that contains the data to be visualized in the chart
  403. */
  404. Chartist.getDataArray = function(data, reverse, multi) {
  405. // Recursively walks through nested arrays and convert string values to numbers and objects with value properties
  406. // to values. Check the tests in data core -> data normalization for a detailed specification of expected values
  407. function recursiveConvert(value) {
  408. if(Chartist.safeHasProperty(value, 'value')) {
  409. // We are dealing with value object notation so we need to recurse on value property
  410. return recursiveConvert(value.value);
  411. } else if(Chartist.safeHasProperty(value, 'data')) {
  412. // We are dealing with series object notation so we need to recurse on data property
  413. return recursiveConvert(value.data);
  414. } else if(value instanceof Array) {
  415. // Data is of type array so we need to recurse on the series
  416. return value.map(recursiveConvert);
  417. } else if(Chartist.isDataHoleValue(value)) {
  418. // We're dealing with a hole in the data and therefore need to return undefined
  419. // We're also returning undefined for multi value output
  420. return undefined;
  421. } else {
  422. // We need to prepare multi value output (x and y data)
  423. if(multi) {
  424. var multiValue = {};
  425. // Single series value arrays are assumed to specify the Y-Axis value
  426. // For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}]
  427. // If multi is a string then it's assumed that it specified which dimension should be filled as default
  428. if(typeof multi === 'string') {
  429. multiValue[multi] = Chartist.getNumberOrUndefined(value);
  430. } else {
  431. multiValue.y = Chartist.getNumberOrUndefined(value);
  432. }
  433. multiValue.x = value.hasOwnProperty('x') ? Chartist.getNumberOrUndefined(value.x) : multiValue.x;
  434. multiValue.y = value.hasOwnProperty('y') ? Chartist.getNumberOrUndefined(value.y) : multiValue.y;
  435. return multiValue;
  436. } else {
  437. // We can return simple data
  438. return Chartist.getNumberOrUndefined(value);
  439. }
  440. }
  441. }
  442. return data.series.map(recursiveConvert);
  443. };
  444. /**
  445. * Converts a number into a padding object.
  446. *
  447. * @memberof Chartist.Core
  448. * @param {Object|Number} padding
  449. * @param {Number} [fallback] This value is used to fill missing values if a incomplete padding object was passed
  450. * @returns {Object} Returns a padding object containing top, right, bottom, left properties filled with the padding number passed in as argument. If the argument is something else than a number (presumably already a correct padding object) then this argument is directly returned.
  451. */
  452. Chartist.normalizePadding = function(padding, fallback) {
  453. fallback = fallback || 0;
  454. return typeof padding === 'number' ? {
  455. top: padding,
  456. right: padding,
  457. bottom: padding,
  458. left: padding
  459. } : {
  460. top: typeof padding.top === 'number' ? padding.top : fallback,
  461. right: typeof padding.right === 'number' ? padding.right : fallback,
  462. bottom: typeof padding.bottom === 'number' ? padding.bottom : fallback,
  463. left: typeof padding.left === 'number' ? padding.left : fallback
  464. };
  465. };
  466. Chartist.getMetaData = function(series, index) {
  467. var value = series.data ? series.data[index] : series[index];
  468. return value ? value.meta : undefined;
  469. };
  470. /**
  471. * Calculate the order of magnitude for the chart scale
  472. *
  473. * @memberof Chartist.Core
  474. * @param {Number} value The value Range of the chart
  475. * @return {Number} The order of magnitude
  476. */
  477. Chartist.orderOfMagnitude = function (value) {
  478. return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
  479. };
  480. /**
  481. * Project a data length into screen coordinates (pixels)
  482. *
  483. * @memberof Chartist.Core
  484. * @param {Object} axisLength The svg element for the chart
  485. * @param {Number} length Single data value from a series array
  486. * @param {Object} bounds All the values to set the bounds of the chart
  487. * @return {Number} The projected data length in pixels
  488. */
  489. Chartist.projectLength = function (axisLength, length, bounds) {
  490. return length / bounds.range * axisLength;
  491. };
  492. /**
  493. * Get the height of the area in the chart for the data series
  494. *
  495. * @memberof Chartist.Core
  496. * @param {Object} svg The svg element for the chart
  497. * @param {Object} options The Object that contains all the optional values for the chart
  498. * @return {Number} The height of the area in the chart for the data series
  499. */
  500. Chartist.getAvailableHeight = function (svg, options) {
  501. return Math.max((Chartist.quantity(options.height).value || svg.height()) - (options.chartPadding.top + options.chartPadding.bottom) - options.axisX.offset, 0);
  502. };
  503. /**
  504. * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
  505. *
  506. * @memberof Chartist.Core
  507. * @param {Array} data The array that contains the data to be visualized in the chart
  508. * @param {Object} options The Object that contains the chart options
  509. * @param {String} dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration
  510. * @return {Object} An object that contains the highest and lowest value that will be visualized on the chart.
  511. */
  512. Chartist.getHighLow = function (data, options, dimension) {
  513. // TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred
  514. options = Chartist.extend({}, options, dimension ? options['axis' + dimension.toUpperCase()] : {});
  515. var highLow = {
  516. high: options.high === undefined ? -Number.MAX_VALUE : +options.high,
  517. low: options.low === undefined ? Number.MAX_VALUE : +options.low
  518. };
  519. var findHigh = options.high === undefined;
  520. var findLow = options.low === undefined;
  521. // Function to recursively walk through arrays and find highest and lowest number
  522. function recursiveHighLow(data) {
  523. if(data === undefined) {
  524. return undefined;
  525. } else if(data instanceof Array) {
  526. for (var i = 0; i < data.length; i++) {
  527. recursiveHighLow(data[i]);
  528. }
  529. } else {
  530. var value = dimension ? +data[dimension] : +data;
  531. if (findHigh && value > highLow.high) {
  532. highLow.high = value;
  533. }
  534. if (findLow && value < highLow.low) {
  535. highLow.low = value;
  536. }
  537. }
  538. }
  539. // Start to find highest and lowest number recursively
  540. if(findHigh || findLow) {
  541. recursiveHighLow(data);
  542. }
  543. // Overrides of high / low based on reference value, it will make sure that the invisible reference value is
  544. // used to generate the chart. This is useful when the chart always needs to contain the position of the
  545. // invisible reference value in the view i.e. for bipolar scales.
  546. if (options.referenceValue || options.referenceValue === 0) {
  547. highLow.high = Math.max(options.referenceValue, highLow.high);
  548. highLow.low = Math.min(options.referenceValue, highLow.low);
  549. }
  550. // If high and low are the same because of misconfiguration or flat data (only the same value) we need
  551. // to set the high or low to 0 depending on the polarity
  552. if (highLow.high <= highLow.low) {
  553. // If both values are 0 we set high to 1
  554. if (highLow.low === 0) {
  555. highLow.high = 1;
  556. } else if (highLow.low < 0) {
  557. // If we have the same negative value for the bounds we set bounds.high to 0
  558. highLow.high = 0;
  559. } else if (highLow.high > 0) {
  560. // If we have the same positive value for the bounds we set bounds.low to 0
  561. highLow.low = 0;
  562. } else {
  563. // If data array was empty, values are Number.MAX_VALUE and -Number.MAX_VALUE. Set bounds to prevent errors
  564. highLow.high = 1;
  565. highLow.low = 0;
  566. }
  567. }
  568. return highLow;
  569. };
  570. /**
  571. * Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.
  572. *
  573. * @memberof Chartist.Core
  574. * @param value
  575. * @returns {Boolean}
  576. */
  577. Chartist.isNumeric = function(value) {
  578. return value === null ? false : isFinite(value);
  579. };
  580. /**
  581. * Returns true on all falsey values except the numeric value 0.
  582. *
  583. * @memberof Chartist.Core
  584. * @param value
  585. * @returns {boolean}
  586. */
  587. Chartist.isFalseyButZero = function(value) {
  588. return !value && value !== 0;
  589. };
  590. /**
  591. * Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.
  592. *
  593. * @memberof Chartist.Core
  594. * @param value
  595. * @returns {*}
  596. */
  597. Chartist.getNumberOrUndefined = function(value) {
  598. return Chartist.isNumeric(value) ? +value : undefined;
  599. };
  600. /**
  601. * Checks if provided value object is multi value (contains x or y properties)
  602. *
  603. * @memberof Chartist.Core
  604. * @param value
  605. */
  606. Chartist.isMultiValue = function(value) {
  607. return typeof value === 'object' && ('x' in value || 'y' in value);
  608. };
  609. /**
  610. * Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`.
  611. *
  612. * @memberof Chartist.Core
  613. * @param value
  614. * @param dimension
  615. * @param defaultValue
  616. * @returns {*}
  617. */
  618. Chartist.getMultiValue = function(value, dimension) {
  619. if(Chartist.isMultiValue(value)) {
  620. return Chartist.getNumberOrUndefined(value[dimension || 'y']);
  621. } else {
  622. return Chartist.getNumberOrUndefined(value);
  623. }
  624. };
  625. /**
  626. * Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.
  627. *
  628. * @memberof Chartist.Core
  629. * @param {Number} num An integer number where the smallest factor should be searched for
  630. * @returns {Number} The smallest integer factor of the parameter num.
  631. */
  632. Chartist.rho = function(num) {
  633. if(num === 1) {
  634. return num;
  635. }
  636. function gcd(p, q) {
  637. if (p % q === 0) {
  638. return q;
  639. } else {
  640. return gcd(q, p % q);
  641. }
  642. }
  643. function f(x) {
  644. return x * x + 1;
  645. }
  646. var x1 = 2, x2 = 2, divisor;
  647. if (num % 2 === 0) {
  648. return 2;
  649. }
  650. do {
  651. x1 = f(x1) % num;
  652. x2 = f(f(x2)) % num;
  653. divisor = gcd(Math.abs(x1 - x2), num);
  654. } while (divisor === 1);
  655. return divisor;
  656. };
  657. /**
  658. * Calculate and retrieve all the bounds for the chart and return them in one array
  659. *
  660. * @memberof Chartist.Core
  661. * @param {Number} axisLength The length of the Axis used for
  662. * @param {Object} highLow An object containing a high and low property indicating the value range of the chart.
  663. * @param {Number} scaleMinSpace The minimum projected length a step should result in
  664. * @param {Boolean} onlyInteger
  665. * @return {Object} All the values to set the bounds of the chart
  666. */
  667. Chartist.getBounds = function (axisLength, highLow, scaleMinSpace, onlyInteger) {
  668. var i,
  669. optimizationCounter = 0,
  670. newMin,
  671. newMax,
  672. bounds = {
  673. high: highLow.high,
  674. low: highLow.low
  675. };
  676. bounds.valueRange = bounds.high - bounds.low;
  677. bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange);
  678. bounds.step = Math.pow(10, bounds.oom);
  679. bounds.min = Math.floor(bounds.low / bounds.step) * bounds.step;
  680. bounds.max = Math.ceil(bounds.high / bounds.step) * bounds.step;
  681. bounds.range = bounds.max - bounds.min;
  682. bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
  683. // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
  684. // If we are already below the scaleMinSpace value we will scale up
  685. var length = Chartist.projectLength(axisLength, bounds.step, bounds);
  686. var scaleUp = length < scaleMinSpace;
  687. var smallestFactor = onlyInteger ? Chartist.rho(bounds.range) : 0;
  688. // First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1
  689. if(onlyInteger && Chartist.projectLength(axisLength, 1, bounds) >= scaleMinSpace) {
  690. bounds.step = 1;
  691. } else if(onlyInteger && smallestFactor < bounds.step && Chartist.projectLength(axisLength, smallestFactor, bounds) >= scaleMinSpace) {
  692. // If step 1 was too small, we can try the smallest factor of range
  693. // If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor
  694. // is larger than the scaleMinSpace we should go for it.
  695. bounds.step = smallestFactor;
  696. } else {
  697. // Trying to divide or multiply by 2 and find the best step value
  698. while (true) {
  699. if (scaleUp && Chartist.projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace) {
  700. bounds.step *= 2;
  701. } else if (!scaleUp && Chartist.projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace) {
  702. bounds.step /= 2;
  703. if(onlyInteger && bounds.step % 1 !== 0) {
  704. bounds.step *= 2;
  705. break;
  706. }
  707. } else {
  708. break;
  709. }
  710. if(optimizationCounter++ > 1000) {
  711. throw new Error('Exceeded maximum number of iterations while optimizing scale step!');
  712. }
  713. }
  714. }
  715. var EPSILON = 2.221E-16;
  716. bounds.step = Math.max(bounds.step, EPSILON);
  717. function safeIncrement(value, increment) {
  718. // If increment is too small use *= (1+EPSILON) as a simple nextafter
  719. if (value === (value += increment)) {
  720. value *= (1 + (increment > 0 ? EPSILON : -EPSILON));
  721. }
  722. return value;
  723. }
  724. // Narrow min and max based on new step
  725. newMin = bounds.min;
  726. newMax = bounds.max;
  727. while (newMin + bounds.step <= bounds.low) {
  728. newMin = safeIncrement(newMin, bounds.step);
  729. }
  730. while (newMax - bounds.step >= bounds.high) {
  731. newMax = safeIncrement(newMax, -bounds.step);
  732. }
  733. bounds.min = newMin;
  734. bounds.max = newMax;
  735. bounds.range = bounds.max - bounds.min;
  736. var values = [];
  737. for (i = bounds.min; i <= bounds.max; i = safeIncrement(i, bounds.step)) {
  738. var value = Chartist.roundWithPrecision(i);
  739. if (value !== values[values.length - 1]) {
  740. values.push(value);
  741. }
  742. }
  743. bounds.values = values;
  744. return bounds;
  745. };
  746. /**
  747. * Calculate cartesian coordinates of polar coordinates
  748. *
  749. * @memberof Chartist.Core
  750. * @param {Number} centerX X-axis coordinates of center point of circle segment
  751. * @param {Number} centerY X-axis coordinates of center point of circle segment
  752. * @param {Number} radius Radius of circle segment
  753. * @param {Number} angleInDegrees Angle of circle segment in degrees
  754. * @return {{x:Number, y:Number}} Coordinates of point on circumference
  755. */
  756. Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
  757. var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
  758. return {
  759. x: centerX + (radius * Math.cos(angleInRadians)),
  760. y: centerY + (radius * Math.sin(angleInRadians))
  761. };
  762. };
  763. /**
  764. * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
  765. *
  766. * @memberof Chartist.Core
  767. * @param {Object} svg The svg element for the chart
  768. * @param {Object} options The Object that contains all the optional values for the chart
  769. * @param {Number} [fallbackPadding] The fallback padding if partial padding objects are used
  770. * @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements
  771. */
  772. Chartist.createChartRect = function (svg, options, fallbackPadding) {
  773. var hasAxis = !!(options.axisX || options.axisY);
  774. var yAxisOffset = hasAxis ? options.axisY.offset : 0;
  775. var xAxisOffset = hasAxis ? options.axisX.offset : 0;
  776. // If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0
  777. var width = svg.width() || Chartist.quantity(options.width).value || 0;
  778. var height = svg.height() || Chartist.quantity(options.height).value || 0;
  779. var normalizedPadding = Chartist.normalizePadding(options.chartPadding, fallbackPadding);
  780. // If settings were to small to cope with offset (legacy) and padding, we'll adjust
  781. width = Math.max(width, yAxisOffset + normalizedPadding.left + normalizedPadding.right);
  782. height = Math.max(height, xAxisOffset + normalizedPadding.top + normalizedPadding.bottom);
  783. var chartRect = {
  784. padding: normalizedPadding,
  785. width: function () {
  786. return this.x2 - this.x1;
  787. },
  788. height: function () {
  789. return this.y1 - this.y2;
  790. }
  791. };
  792. if(hasAxis) {
  793. if (options.axisX.position === 'start') {
  794. chartRect.y2 = normalizedPadding.top + xAxisOffset;
  795. chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
  796. } else {
  797. chartRect.y2 = normalizedPadding.top;
  798. chartRect.y1 = Math.max(height - normalizedPadding.bottom - xAxisOffset, chartRect.y2 + 1);
  799. }
  800. if (options.axisY.position === 'start') {
  801. chartRect.x1 = normalizedPadding.left + yAxisOffset;
  802. chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
  803. } else {
  804. chartRect.x1 = normalizedPadding.left;
  805. chartRect.x2 = Math.max(width - normalizedPadding.right - yAxisOffset, chartRect.x1 + 1);
  806. }
  807. } else {
  808. chartRect.x1 = normalizedPadding.left;
  809. chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
  810. chartRect.y2 = normalizedPadding.top;
  811. chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
  812. }
  813. return chartRect;
  814. };
  815. /**
  816. * Creates a grid line based on a projected value.
  817. *
  818. * @memberof Chartist.Core
  819. * @param position
  820. * @param index
  821. * @param axis
  822. * @param offset
  823. * @param length
  824. * @param group
  825. * @param classes
  826. * @param eventEmitter
  827. */
  828. Chartist.createGrid = function(position, index, axis, offset, length, group, classes, eventEmitter) {
  829. var positionalData = {};
  830. positionalData[axis.units.pos + '1'] = position;
  831. positionalData[axis.units.pos + '2'] = position;
  832. positionalData[axis.counterUnits.pos + '1'] = offset;
  833. positionalData[axis.counterUnits.pos + '2'] = offset + length;
  834. var gridElement = group.elem('line', positionalData, classes.join(' '));
  835. // Event for grid draw
  836. eventEmitter.emit('draw',
  837. Chartist.extend({
  838. type: 'grid',
  839. axis: axis,
  840. index: index,
  841. group: group,
  842. element: gridElement
  843. }, positionalData)
  844. );
  845. };
  846. /**
  847. * Creates a grid background rect and emits the draw event.
  848. *
  849. * @memberof Chartist.Core
  850. * @param gridGroup
  851. * @param chartRect
  852. * @param className
  853. * @param eventEmitter
  854. */
  855. Chartist.createGridBackground = function (gridGroup, chartRect, className, eventEmitter) {
  856. var gridBackground = gridGroup.elem('rect', {
  857. x: chartRect.x1,
  858. y: chartRect.y2,
  859. width: chartRect.width(),
  860. height: chartRect.height(),
  861. }, className, true);
  862. // Event for grid background draw
  863. eventEmitter.emit('draw', {
  864. type: 'gridBackground',
  865. group: gridGroup,
  866. element: gridBackground
  867. });
  868. };
  869. /**
  870. * Creates a label based on a projected value and an axis.
  871. *
  872. * @memberof Chartist.Core
  873. * @param position
  874. * @param length
  875. * @param index
  876. * @param labels
  877. * @param axis
  878. * @param axisOffset
  879. * @param labelOffset
  880. * @param group
  881. * @param classes
  882. * @param useForeignObject
  883. * @param eventEmitter
  884. */
  885. Chartist.createLabel = function(position, length, index, labels, axis, axisOffset, labelOffset, group, classes, useForeignObject, eventEmitter) {
  886. var labelElement;
  887. var positionalData = {};
  888. positionalData[axis.units.pos] = position + labelOffset[axis.units.pos];
  889. positionalData[axis.counterUnits.pos] = labelOffset[axis.counterUnits.pos];
  890. positionalData[axis.units.len] = length;
  891. positionalData[axis.counterUnits.len] = Math.max(0, axisOffset - 10);
  892. if(useForeignObject) {
  893. // We need to set width and height explicitly to px as span will not expand with width and height being
  894. // 100% in all browsers
  895. var content = document.createElement('span');
  896. content.className = classes.join(' ');
  897. content.setAttribute('xmlns', Chartist.namespaces.xhtml);
  898. content.innerText = labels[index];
  899. content.style[axis.units.len] = Math.round(positionalData[axis.units.len]) + 'px';
  900. content.style[axis.counterUnits.len] = Math.round(positionalData[axis.counterUnits.len]) + 'px';
  901. labelElement = group.foreignObject(content, Chartist.extend({
  902. style: 'overflow: visible;'
  903. }, positionalData));
  904. } else {
  905. labelElement = group.elem('text', positionalData, classes.join(' ')).text(labels[index]);
  906. }
  907. eventEmitter.emit('draw', Chartist.extend({
  908. type: 'label',
  909. axis: axis,
  910. index: index,
  911. group: group,
  912. element: labelElement,
  913. text: labels[index]
  914. }, positionalData));
  915. };
  916. /**
  917. * Helper to read series specific options from options object. It automatically falls back to the global option if
  918. * there is no option in the series options.
  919. *
  920. * @param {Object} series Series object
  921. * @param {Object} options Chartist options object
  922. * @param {string} key The options key that should be used to obtain the options
  923. * @returns {*}
  924. */
  925. Chartist.getSeriesOption = function(series, options, key) {
  926. if(series.name && options.series && options.series[series.name]) {
  927. var seriesOptions = options.series[series.name];
  928. return seriesOptions.hasOwnProperty(key) ? seriesOptions[key] : options[key];
  929. } else {
  930. return options[key];
  931. }
  932. };
  933. /**
  934. * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
  935. *
  936. * @memberof Chartist.Core
  937. * @param {Object} options Options set by user
  938. * @param {Array} responsiveOptions Optional functions to add responsive behavior to chart
  939. * @param {Object} eventEmitter The event emitter that will be used to emit the options changed events
  940. * @return {Object} The consolidated options object from the defaults, base and matching responsive options
  941. */
  942. Chartist.optionsProvider = function (options, responsiveOptions, eventEmitter) {
  943. var baseOptions = Chartist.extend({}, options),
  944. currentOptions,
  945. mediaQueryListeners = [],
  946. i;
  947. function updateCurrentOptions(mediaEvent) {
  948. var previousOptions = currentOptions;
  949. currentOptions = Chartist.extend({}, baseOptions);
  950. if (responsiveOptions) {
  951. for (i = 0; i < responsiveOptions.length; i++) {
  952. var mql = window.matchMedia(responsiveOptions[i][0]);
  953. if (mql.matches) {
  954. currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]);
  955. }
  956. }
  957. }
  958. if(eventEmitter && mediaEvent) {
  959. eventEmitter.emit('optionsChanged', {
  960. previousOptions: previousOptions,
  961. currentOptions: currentOptions
  962. });
  963. }
  964. }
  965. function removeMediaQueryListeners() {
  966. mediaQueryListeners.forEach(function(mql) {
  967. mql.removeListener(updateCurrentOptions);
  968. });
  969. }
  970. if (!window.matchMedia) {
  971. throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';
  972. } else if (responsiveOptions) {
  973. for (i = 0; i < responsiveOptions.length; i++) {
  974. var mql = window.matchMedia(responsiveOptions[i][0]);
  975. mql.addListener(updateCurrentOptions);
  976. mediaQueryListeners.push(mql);
  977. }
  978. }
  979. // Execute initially without an event argument so we get the correct options
  980. updateCurrentOptions();
  981. return {
  982. removeMediaQueryListeners: removeMediaQueryListeners,
  983. getCurrentOptions: function getCurrentOptions() {
  984. return Chartist.extend({}, currentOptions);
  985. }
  986. };
  987. };
  988. /**
  989. * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates
  990. * valueData property describing the segment.
  991. *
  992. * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any
  993. * points with undefined values are discarded.
  994. *
  995. * **Options**
  996. * The following options are used to determine how segments are formed
  997. * ```javascript
  998. * var options = {
  999. * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.
  1000. * fillHoles: false,
  1001. * // If increasingX is true, the coordinates in all segments have strictly increasing x-values.
  1002. * increasingX: false
  1003. * };
  1004. * ```
  1005. *
  1006. * @memberof Chartist.Core
  1007. * @param {Array} pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn]
  1008. * @param {Array} values List of associated point values in the form [v1, v2 .. vn]
  1009. * @param {Object} options Options set by user
  1010. * @return {Array} List of segments, each containing a pathCoordinates and valueData property.
  1011. */
  1012. Chartist.splitIntoSegments = function(pathCoordinates, valueData, options) {
  1013. var defaultOptions = {
  1014. increasingX: false,
  1015. fillHoles: false
  1016. };
  1017. options = Chartist.extend({}, defaultOptions, options);
  1018. var segments = [];
  1019. var hole = true;
  1020. for(var i = 0; i < pathCoordinates.length; i += 2) {
  1021. // If this value is a "hole" we set the hole flag
  1022. if(Chartist.getMultiValue(valueData[i / 2].value) === undefined) {
  1023. // if(valueData[i / 2].value === undefined) {
  1024. if(!options.fillHoles) {
  1025. hole = true;
  1026. }
  1027. } else {
  1028. if(options.increasingX && i >= 2 && pathCoordinates[i] <= pathCoordinates[i-2]) {
  1029. // X is not increasing, so we need to make sure we start a new segment
  1030. hole = true;
  1031. }
  1032. // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment
  1033. if(hole) {
  1034. segments.push({
  1035. pathCoordinates: [],
  1036. valueData: []
  1037. });
  1038. // As we have a valid value now, we are not in a "hole" anymore
  1039. hole = false;
  1040. }
  1041. // Add to the segment pathCoordinates and valueData
  1042. segments[segments.length - 1].pathCoordinates.push(pathCoordinates[i], pathCoordinates[i + 1]);
  1043. segments[segments.length - 1].valueData.push(valueData[i / 2]);
  1044. }
  1045. }
  1046. return segments;
  1047. };
  1048. }(window, document, Chartist));
  1049. ;/**
  1050. * Chartist path interpolation functions.
  1051. *
  1052. * @module Chartist.Interpolation
  1053. */
  1054. /* global Chartist */
  1055. (function(window, document, Chartist) {
  1056. 'use strict';
  1057. Chartist.Interpolation = {};
  1058. /**
  1059. * This interpolation function does not smooth the path and the result is only containing lines and no curves.
  1060. *
  1061. * @example
  1062. * var chart = new Chartist.Line('.ct-chart', {
  1063. * labels: [1, 2, 3, 4, 5],
  1064. * series: [[1, 2, 8, 1, 7]]
  1065. * }, {
  1066. * lineSmooth: Chartist.Interpolation.none({
  1067. * fillHoles: false
  1068. * })
  1069. * });
  1070. *
  1071. *
  1072. * @memberof Chartist.Interpolation
  1073. * @return {Function}
  1074. */
  1075. Chartist.Interpolation.none = function(options) {
  1076. var defaultOptions = {
  1077. fillHoles: false
  1078. };
  1079. options = Chartist.extend({}, defaultOptions, options);
  1080. return function none(pathCoordinates, valueData) {
  1081. var path = new Chartist.Svg.Path();
  1082. var hole = true;
  1083. for(var i = 0; i < pathCoordinates.length; i += 2) {
  1084. var currX = pathCoordinates[i];
  1085. var currY = pathCoordinates[i + 1];
  1086. var currData = valueData[i / 2];
  1087. if(Chartist.getMultiValue(currData.value) !== undefined) {
  1088. if(hole) {
  1089. path.move(currX, currY, false, currData);
  1090. } else {
  1091. path.line(currX, currY, false, currData);
  1092. }
  1093. hole = false;
  1094. } else if(!options.fillHoles) {
  1095. hole = true;
  1096. }
  1097. }
  1098. return path;
  1099. };
  1100. };
  1101. /**
  1102. * Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing.
  1103. *
  1104. * Simple smoothing can be used instead of `Chartist.Smoothing.cardinal` if you'd like to get rid of the artifacts it produces sometimes. Simple smoothing produces less flowing lines but is accurate by hitting the points and it also doesn't swing below or above the given data point.
  1105. *
  1106. * All smoothing functions within Chartist are factory functions that accept an options parameter. The simple interpolation function accepts one configuration parameter `divisor`, between 1 and ∞, which controls the smoothing characteristics.
  1107. *
  1108. * @example
  1109. * var chart = new Chartist.Line('.ct-chart', {
  1110. * labels: [1, 2, 3, 4, 5],
  1111. * series: [[1, 2, 8, 1, 7]]
  1112. * }, {
  1113. * lineSmooth: Chartist.Interpolation.simple({
  1114. * divisor: 2,
  1115. * fillHoles: false
  1116. * })
  1117. * });
  1118. *
  1119. *
  1120. * @memberof Chartist.Interpolation
  1121. * @param {Object} options The options of the simple interpolation factory function.
  1122. * @return {Function}
  1123. */
  1124. Chartist.Interpolation.simple = function(options) {
  1125. var defaultOptions = {
  1126. divisor: 2,
  1127. fillHoles: false
  1128. };
  1129. options = Chartist.extend({}, defaultOptions, options);
  1130. var d = 1 / Math.max(1, options.divisor);
  1131. return function simple(pathCoordinates, valueData) {
  1132. var path = new Chartist.Svg.Path();
  1133. var prevX, prevY, prevData;
  1134. for(var i = 0; i < pathCoordinates.length; i += 2) {
  1135. var currX = pathCoordinates[i];
  1136. var currY = pathCoordinates[i + 1];
  1137. var length = (currX - prevX) * d;
  1138. var currData = valueData[i / 2];
  1139. if(currData.value !== undefined) {
  1140. if(prevData === undefined) {
  1141. path.move(currX, currY, false, currData);
  1142. } else {
  1143. path.curve(
  1144. prevX + length,
  1145. prevY,
  1146. currX - length,
  1147. currY,
  1148. currX,
  1149. currY,
  1150. false,
  1151. currData
  1152. );
  1153. }
  1154. prevX = currX;
  1155. prevY = currY;
  1156. prevData = currData;
  1157. } else if(!options.fillHoles) {
  1158. prevX = currX = prevData = undefined;
  1159. }
  1160. }
  1161. return path;
  1162. };
  1163. };
  1164. /**
  1165. * Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results.
  1166. *
  1167. * Cardinal splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
  1168. *
  1169. * All smoothing functions within Chartist are factory functions that accept an options parameter. The cardinal interpolation function accepts one configuration parameter `tension`, between 0 and 1, which controls the smoothing intensity.
  1170. *
  1171. * @example
  1172. * var chart = new Chartist.Line('.ct-chart', {
  1173. * labels: [1, 2, 3, 4, 5],
  1174. * series: [[1, 2, 8, 1, 7]]
  1175. * }, {
  1176. * lineSmooth: Chartist.Interpolation.cardinal({
  1177. * tension: 1,
  1178. * fillHoles: false
  1179. * })
  1180. * });
  1181. *
  1182. * @memberof Chartist.Interpolation
  1183. * @param {Object} options The options of the cardinal factory function.
  1184. * @return {Function}
  1185. */
  1186. Chartist.Interpolation.cardinal = function(options) {
  1187. var defaultOptions = {
  1188. tension: 1,
  1189. fillHoles: false
  1190. };
  1191. options = Chartist.extend({}, defaultOptions, options);
  1192. var t = Math.min(1, Math.max(0, options.tension)),
  1193. c = 1 - t;
  1194. return function cardinal(pathCoordinates, valueData) {
  1195. // First we try to split the coordinates into segments
  1196. // This is necessary to treat "holes" in line charts
  1197. var segments = Chartist.splitIntoSegments(pathCoordinates, valueData, {
  1198. fillHoles: options.fillHoles
  1199. });
  1200. if(!segments.length) {
  1201. // If there were no segments return 'Chartist.Interpolation.none'
  1202. return Chartist.Interpolation.none()([]);
  1203. } else if(segments.length > 1) {
  1204. // If the split resulted in more that one segment we need to interpolate each segment individually and join them
  1205. // afterwards together into a single path.
  1206. var paths = [];
  1207. // For each segment we will recurse the cardinal function
  1208. segments.forEach(function(segment) {
  1209. paths.push(cardinal(segment.pathCoordinates, segment.valueData));
  1210. });
  1211. // Join the segment path data into a single path and return
  1212. return Chartist.Svg.Path.join(paths);
  1213. } else {
  1214. // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
  1215. // segment
  1216. pathCoordinates = segments[0].pathCoordinates;
  1217. valueData = segments[0].valueData;
  1218. // If less than two points we need to fallback to no smoothing
  1219. if(pathCoordinates.length <= 4) {
  1220. return Chartist.Interpolation.none()(pathCoordinates, valueData);
  1221. }
  1222. var path = new Chartist.Svg.Path().move(pathCoordinates[0], pathCoordinates[1], false, valueData[0]),
  1223. z;
  1224. for (var i = 0, iLen = pathCoordinates.length; iLen - 2 * !z > i; i += 2) {
  1225. var p = [
  1226. {x: +pathCoordinates[i - 2], y: +pathCoordinates[i - 1]},
  1227. {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]},
  1228. {x: +pathCoordinates[i + 2], y: +pathCoordinates[i + 3]},
  1229. {x: +pathCoordinates[i + 4], y: +pathCoordinates[i + 5]}
  1230. ];
  1231. if (z) {
  1232. if (!i) {
  1233. p[0] = {x: +pathCoordinates[iLen - 2], y: +pathCoordinates[iLen - 1]};
  1234. } else if (iLen - 4 === i) {
  1235. p[3] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
  1236. } else if (iLen - 2 === i) {
  1237. p[2] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
  1238. p[3] = {x: +pathCoordinates[2], y: +pathCoordinates[3]};
  1239. }
  1240. } else {
  1241. if (iLen - 4 === i) {
  1242. p[3] = p[2];
  1243. } else if (!i) {
  1244. p[0] = {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]};
  1245. }
  1246. }
  1247. path.curve(
  1248. (t * (-p[0].x + 6 * p[1].x + p[2].x) / 6) + (c * p[2].x),
  1249. (t * (-p[0].y + 6 * p[1].y + p[2].y) / 6) + (c * p[2].y),
  1250. (t * (p[1].x + 6 * p[2].x - p[3].x) / 6) + (c * p[2].x),
  1251. (t * (p[1].y + 6 * p[2].y - p[3].y) / 6) + (c * p[2].y),
  1252. p[2].x,
  1253. p[2].y,
  1254. false,
  1255. valueData[(i + 2) / 2]
  1256. );
  1257. }
  1258. return path;
  1259. }
  1260. };
  1261. };
  1262. /**
  1263. * Monotone Cubic spline interpolation produces a smooth curve which preserves monotonicity. Unlike cardinal splines, the curve will not extend beyond the range of y-values of the original data points.
  1264. *
  1265. * Monotone Cubic splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
  1266. *
  1267. * The x-values of subsequent points must be increasing to fit a Monotone Cubic spline. If this condition is not met for a pair of adjacent points, then there will be a break in the curve between those data points.
  1268. *
  1269. * All smoothing functions within Chartist are factory functions that accept an options parameter.
  1270. *
  1271. * @example
  1272. * var chart = new Chartist.Line('.ct-chart', {
  1273. * labels: [1, 2, 3, 4, 5],
  1274. * series: [[1, 2, 8, 1, 7]]
  1275. * }, {
  1276. * lineSmooth: Chartist.Interpolation.monotoneCubic({
  1277. * fillHoles: false
  1278. * })
  1279. * });
  1280. *
  1281. * @memberof Chartist.Interpolation
  1282. * @param {Object} options The options of the monotoneCubic factory function.
  1283. * @return {Function}
  1284. */
  1285. Chartist.Interpolation.monotoneCubic = function(options) {
  1286. var defaultOptions = {
  1287. fillHoles: false
  1288. };
  1289. options = Chartist.extend({}, defaultOptions, options);
  1290. return function monotoneCubic(pathCoordinates, valueData) {
  1291. // First we try to split the coordinates into segments
  1292. // This is necessary to treat "holes" in line charts
  1293. var segments = Chartist.splitIntoSegments(pathCoordinates, valueData, {
  1294. fillHoles: options.fillHoles,
  1295. increasingX: true
  1296. });
  1297. if(!segments.length) {
  1298. // If there were no segments return 'Chartist.Interpolation.none'
  1299. return Chartist.Interpolation.none()([]);
  1300. } else if(segments.length > 1) {
  1301. // If the split resulted in more that one segment we need to interpolate each segment individually and join them
  1302. // afterwards together into a single path.
  1303. var paths = [];
  1304. // For each segment we will recurse the monotoneCubic fn function
  1305. segments.forEach(function(segment) {
  1306. paths.push(monotoneCubic(segment.pathCoordinates, segment.valueData));
  1307. });
  1308. // Join the segment path data into a single path and return
  1309. return Chartist.Svg.Path.join(paths);
  1310. } else {
  1311. // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
  1312. // segment
  1313. pathCoordinates = segments[0].pathCoordinates;
  1314. valueData = segments[0].valueData;
  1315. // If less than three points we need to fallback to no smoothing
  1316. if(pathCoordinates.length <= 4) {
  1317. return Chartist.Interpolation.none()(pathCoordinates, valueData);
  1318. }
  1319. var xs = [],
  1320. ys = [],
  1321. i,
  1322. n = pathCoordinates.length / 2,
  1323. ms = [],
  1324. ds = [], dys = [], dxs = [],
  1325. path;
  1326. // Populate x and y coordinates into separate arrays, for readability
  1327. for(i = 0; i < n; i++) {
  1328. xs[i] = pathCoordinates[i * 2];
  1329. ys[i] = pathCoordinates[i * 2 + 1];
  1330. }
  1331. // Calculate deltas and derivative
  1332. for(i = 0; i < n - 1; i++) {
  1333. dys[i] = ys[i + 1] - ys[i];
  1334. dxs[i] = xs[i + 1] - xs[i];
  1335. ds[i] = dys[i] / dxs[i];
  1336. }
  1337. // Determine desired slope (m) at each point using Fritsch-Carlson method
  1338. // See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation
  1339. ms[0] = ds[0];
  1340. ms[n - 1] = ds[n - 2];
  1341. for(i = 1; i < n - 1; i++) {
  1342. if(ds[i] === 0 || ds[i - 1] === 0 || (ds[i - 1] > 0) !== (ds[i] > 0)) {
  1343. ms[i] = 0;
  1344. } else {
  1345. ms[i] = 3 * (dxs[i - 1] + dxs[i]) / (
  1346. (2 * dxs[i] + dxs[i - 1]) / ds[i - 1] +
  1347. (dxs[i] + 2 * dxs[i - 1]) / ds[i]);
  1348. if(!isFinite(ms[i])) {
  1349. ms[i] = 0;
  1350. }
  1351. }
  1352. }
  1353. // Now build a path from the slopes
  1354. path = new Chartist.Svg.Path().move(xs[0], ys[0], false, valueData[0]);
  1355. for(i = 0; i < n - 1; i++) {
  1356. path.curve(
  1357. // First control point
  1358. xs[i] + dxs[i] / 3,
  1359. ys[i] + ms[i] * dxs[i] / 3,
  1360. // Second control point
  1361. xs[i + 1] - dxs[i] / 3,
  1362. ys[i + 1] - ms[i + 1] * dxs[i] / 3,
  1363. // End point
  1364. xs[i + 1],
  1365. ys[i + 1],
  1366. false,
  1367. valueData[i + 1]
  1368. );
  1369. }
  1370. return path;
  1371. }
  1372. };
  1373. };
  1374. /**
  1375. * Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the `showPoint` option is enabled.
  1376. *
  1377. * All smoothing functions within Chartist are factory functions that accept an options parameter. The step interpolation function accepts one configuration parameter `postpone`, that can be `true` or `false`. The default value is `true` and will cause the step to occur where the value actually changes. If a different behaviour is needed where the step is shifted to the left and happens before the actual value, this option can be set to `false`.
  1378. *
  1379. * @example
  1380. * var chart = new Chartist.Line('.ct-chart', {
  1381. * labels: [1, 2, 3, 4, 5],
  1382. * series: [[1, 2, 8, 1, 7]]
  1383. * }, {
  1384. * lineSmooth: Chartist.Interpolation.step({
  1385. * postpone: true,
  1386. * fillHoles: false
  1387. * })
  1388. * });
  1389. *
  1390. * @memberof Chartist.Interpolation
  1391. * @param options
  1392. * @returns {Function}
  1393. */
  1394. Chartist.Interpolation.step = function(options) {
  1395. var defaultOptions = {
  1396. postpone: true,
  1397. fillHoles: false
  1398. };
  1399. options = Chartist.extend({}, defaultOptions, options);
  1400. return function step(pathCoordinates, valueData) {
  1401. var path = new Chartist.Svg.Path();
  1402. var prevX, prevY, prevData;
  1403. for (var i = 0; i < pathCoordinates.length; i += 2) {
  1404. var currX = pathCoordinates[i];
  1405. var currY = pathCoordinates[i + 1];
  1406. var currData = valueData[i / 2];
  1407. // If the current point is also not a hole we can draw the step lines
  1408. if(currData.value !== undefined) {
  1409. if(prevData === undefined) {
  1410. path.move(currX, currY, false, currData);
  1411. } else {
  1412. if(options.postpone) {
  1413. // If postponed we should draw the step line with the value of the previous value
  1414. path.line(currX, prevY, false, prevData);
  1415. } else {
  1416. // If not postponed we should draw the step line with the value of the current value
  1417. path.line(prevX, currY, false, currData);
  1418. }
  1419. // Line to the actual point (this should only be a Y-Axis movement
  1420. path.line(currX, currY, false, currData);
  1421. }
  1422. prevX = currX;
  1423. prevY = currY;
  1424. prevData = currData;
  1425. } else if(!options.fillHoles) {
  1426. prevX = prevY = prevData = undefined;
  1427. }
  1428. }
  1429. return path;
  1430. };
  1431. };
  1432. }(window, document, Chartist));
  1433. ;/**
  1434. * A very basic event module that helps to generate and catch events.
  1435. *
  1436. * @module Chartist.Event
  1437. */
  1438. /* global Chartist */
  1439. (function (window, document, Chartist) {
  1440. 'use strict';
  1441. Chartist.EventEmitter = function () {
  1442. var handlers = [];
  1443. /**
  1444. * Add an event handler for a specific event
  1445. *
  1446. * @memberof Chartist.Event
  1447. * @param {String} event The event name
  1448. * @param {Function} handler A event handler function
  1449. */
  1450. function addEventHandler(event, handler) {
  1451. handlers[event] = handlers[event] || [];
  1452. handlers[event].push(handler);
  1453. }
  1454. /**
  1455. * Remove an event handler of a specific event name or remove all event handlers for a specific event.
  1456. *
  1457. * @memberof Chartist.Event
  1458. * @param {String} event The event name where a specific or all handlers should be removed
  1459. * @param {Function} [handler] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed.
  1460. */
  1461. function removeEventHandler(event, handler) {
  1462. // Only do something if there are event handlers with this name existing
  1463. if(handlers[event]) {
  1464. // If handler is set we will look for a specific handler and only remove this
  1465. if(handler) {
  1466. handlers[event].splice(handlers[event].indexOf(handler), 1);
  1467. if(handlers[event].length === 0) {
  1468. delete handlers[event];
  1469. }
  1470. } else {
  1471. // If no handler is specified we remove all handlers for this event
  1472. delete handlers[event];
  1473. }
  1474. }
  1475. }
  1476. /**
  1477. * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.
  1478. *
  1479. * @memberof Chartist.Event
  1480. * @param {String} event The event name that should be triggered
  1481. * @param {*} data Arbitrary data that will be passed to the event handler callback functions
  1482. */
  1483. function emit(event, data) {
  1484. // Only do something if there are event handlers with this name existing
  1485. if(handlers[event]) {
  1486. handlers[event].forEach(function(handler) {
  1487. handler(data);
  1488. });
  1489. }
  1490. // Emit event to star event handlers
  1491. if(handlers['*']) {
  1492. handlers['*'].forEach(function(starHandler) {
  1493. starHandler(event, data);
  1494. });
  1495. }
  1496. }
  1497. return {
  1498. addEventHandler: addEventHandler,
  1499. removeEventHandler: removeEventHandler,
  1500. emit: emit
  1501. };
  1502. };
  1503. }(window, document, Chartist));
  1504. ;/**
  1505. * This module provides some basic prototype inheritance utilities.
  1506. *
  1507. * @module Chartist.Class
  1508. */
  1509. /* global Chartist */
  1510. (function(window, document, Chartist) {
  1511. 'use strict';
  1512. function listToArray(list) {
  1513. var arr = [];
  1514. if (list.length) {
  1515. for (var i = 0; i < list.length; i++) {
  1516. arr.push(list[i]);
  1517. }
  1518. }
  1519. return arr;
  1520. }
  1521. /**
  1522. * Method to extend from current prototype.
  1523. *
  1524. * @memberof Chartist.Class
  1525. * @param {Object} properties The object that serves as definition for the prototype that gets created for the new class. This object should always contain a constructor property that is the desired constructor for the newly created class.
  1526. * @param {Object} [superProtoOverride] By default extens will use the current class prototype or Chartist.class. With this parameter you can specify any super prototype that will be used.
  1527. * @return {Function} Constructor function of the new class
  1528. *
  1529. * @example
  1530. * var Fruit = Class.extend({
  1531. * color: undefined,
  1532. * sugar: undefined,
  1533. *
  1534. * constructor: function(color, sugar) {
  1535. * this.color = color;
  1536. * this.sugar = sugar;
  1537. * },
  1538. *
  1539. * eat: function() {
  1540. * this.sugar = 0;
  1541. * return this;
  1542. * }
  1543. * });
  1544. *
  1545. * var Banana = Fruit.extend({
  1546. * length: undefined,
  1547. *
  1548. * constructor: function(length, sugar) {
  1549. * Banana.super.constructor.call(this, 'Yellow', sugar);
  1550. * this.length = length;
  1551. * }
  1552. * });
  1553. *
  1554. * var banana = new Banana(20, 40);
  1555. * console.log('banana instanceof Fruit', banana instanceof Fruit);
  1556. * console.log('Fruit is prototype of banana', Fruit.prototype.isPrototypeOf(banana));
  1557. * console.log('bananas prototype is Fruit', Object.getPrototypeOf(banana) === Fruit.prototype);
  1558. * console.log(banana.sugar);
  1559. * console.log(banana.eat().sugar);
  1560. * console.log(banana.color);
  1561. */
  1562. function extend(properties, superProtoOverride) {
  1563. var superProto = superProtoOverride || this.prototype || Chartist.Class;
  1564. var proto = Object.create(superProto);
  1565. Chartist.Class.cloneDefinitions(proto, properties);
  1566. var constr = function() {
  1567. var fn = proto.constructor || function () {},
  1568. instance;
  1569. // If this is linked to the Chartist namespace the constructor was not called with new
  1570. // To provide a fallback we will instantiate here and return the instance
  1571. instance = this === Chartist ? Object.create(proto) : this;
  1572. fn.apply(instance, Array.prototype.slice.call(arguments, 0));
  1573. // If this constructor was not called with new we need to return the instance
  1574. // This will not harm when the constructor has been called with new as the returned value is ignored
  1575. return instance;
  1576. };
  1577. constr.prototype = proto;
  1578. constr.super = superProto;
  1579. constr.extend = this.extend;
  1580. return constr;
  1581. }
  1582. // Variable argument list clones args > 0 into args[0] and retruns modified args[0]
  1583. function cloneDefinitions() {
  1584. var args = listToArray(arguments);
  1585. var target = args[0];
  1586. args.splice(1, args.length - 1).forEach(function (source) {
  1587. Object.getOwnPropertyNames(source).forEach(function (propName) {
  1588. // If this property already exist in target we delete it first
  1589. delete target[propName];
  1590. // Define the property with the descriptor from source
  1591. Object.defineProperty(target, propName,
  1592. Object.getOwnPropertyDescriptor(source, propName));
  1593. });
  1594. });
  1595. return target;
  1596. }
  1597. Chartist.Class = {
  1598. extend: extend,
  1599. cloneDefinitions: cloneDefinitions
  1600. };
  1601. }(window, document, Chartist));
  1602. ;/**
  1603. * Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
  1604. *
  1605. * @module Chartist.Base
  1606. */
  1607. /* global Chartist */
  1608. (function(window, document, Chartist) {
  1609. 'use strict';
  1610. // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
  1611. // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
  1612. // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
  1613. // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
  1614. // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
  1615. // The problem is with the label offsets that can't be converted into percentage and affecting the chart container
  1616. /**
  1617. * Updates the chart which currently does a full reconstruction of the SVG DOM
  1618. *
  1619. * @param {Object} [data] Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
  1620. * @param {Object} [options] Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.
  1621. * @param {Boolean} [override] If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base
  1622. * @memberof Chartist.Base
  1623. */
  1624. function update(data, options, override) {
  1625. if(data) {
  1626. this.data = data || {};
  1627. this.data.labels = this.data.labels || [];
  1628. this.data.series = this.data.series || [];
  1629. // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
  1630. this.eventEmitter.emit('data', {
  1631. type: 'update',
  1632. data: this.data
  1633. });
  1634. }
  1635. if(options) {
  1636. this.options = Chartist.extend({}, override ? this.options : this.defaultOptions, options);
  1637. // If chartist was not initialized yet, we just set the options and leave the rest to the initialization
  1638. // Otherwise we re-create the optionsProvider at this point
  1639. if(!this.initializeTimeoutId) {
  1640. this.optionsProvider.removeMediaQueryListeners();
  1641. this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
  1642. }
  1643. }
  1644. // Only re-created the chart if it has been initialized yet
  1645. if(!this.initializeTimeoutId) {
  1646. this.createChart(this.optionsProvider.getCurrentOptions());
  1647. }
  1648. // Return a reference to the chart object to chain up calls
  1649. return this;
  1650. }
  1651. /**
  1652. * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
  1653. *
  1654. * @memberof Chartist.Base
  1655. */
  1656. function detach() {
  1657. // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore
  1658. // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout
  1659. if(!this.initializeTimeoutId) {
  1660. window.removeEventListener('resize', this.resizeListener);
  1661. this.optionsProvider.removeMediaQueryListeners();
  1662. } else {
  1663. window.clearTimeout(this.initializeTimeoutId);
  1664. }
  1665. return this;
  1666. }
  1667. /**
  1668. * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
  1669. *
  1670. * @memberof Chartist.Base
  1671. * @param {String} event Name of the event. Check the examples for supported events.
  1672. * @param {Function} handler The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
  1673. */
  1674. function on(event, handler) {
  1675. this.eventEmitter.addEventHandler(event, handler);
  1676. return this;
  1677. }
  1678. /**
  1679. * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
  1680. *
  1681. * @memberof Chartist.Base
  1682. * @param {String} event Name of the event for which a handler should be removed
  1683. * @param {Function} [handler] The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.
  1684. */
  1685. function off(event, handler) {
  1686. this.eventEmitter.removeEventHandler(event, handler);
  1687. return this;
  1688. }
  1689. function initialize() {
  1690. // Add window resize listener that re-creates the chart
  1691. window.addEventListener('resize', this.resizeListener);
  1692. // Obtain current options based on matching media queries (if responsive options are given)
  1693. // This will also register a listener that is re-creating the chart based on media changes
  1694. this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
  1695. // Register options change listener that will trigger a chart update
  1696. this.eventEmitter.addEventHandler('optionsChanged', function() {
  1697. this.update();
  1698. }.bind(this));
  1699. // Before the first chart creation we need to register us with all plugins that are configured
  1700. // Initialize all relevant plugins with our chart object and the plugin options specified in the config
  1701. if(this.options.plugins) {
  1702. this.options.plugins.forEach(function(plugin) {
  1703. if(plugin instanceof Array) {
  1704. plugin[0](this, plugin[1]);
  1705. } else {
  1706. plugin(this);
  1707. }
  1708. }.bind(this));
  1709. }
  1710. // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
  1711. this.eventEmitter.emit('data', {
  1712. type: 'initial',
  1713. data: this.data
  1714. });
  1715. // Create the first chart
  1716. this.createChart(this.optionsProvider.getCurrentOptions());
  1717. // As chart is initialized from the event loop now we can reset our timeout reference
  1718. // This is important if the chart gets initialized on the same element twice
  1719. this.initializeTimeoutId = undefined;
  1720. }
  1721. /**
  1722. * Constructor of chart base class.
  1723. *
  1724. * @param query
  1725. * @param data
  1726. * @param defaultOptions
  1727. * @param options
  1728. * @param responsiveOptions
  1729. * @constructor
  1730. */
  1731. function Base(query, data, defaultOptions, options, responsiveOptions) {
  1732. this.container = Chartist.querySelector(query);
  1733. this.data = data || {};
  1734. this.data.labels = this.data.labels || [];
  1735. this.data.series = this.data.series || [];
  1736. this.defaultOptions = defaultOptions;
  1737. this.options = options;
  1738. this.responsiveOptions = responsiveOptions;
  1739. this.eventEmitter = Chartist.EventEmitter();
  1740. this.supportsForeignObject = Chartist.Svg.isSupported('Extensibility');
  1741. this.supportsAnimations = Chartist.Svg.isSupported('AnimationEventsAttribute');
  1742. this.resizeListener = function resizeListener(){
  1743. this.update();
  1744. }.bind(this);
  1745. if(this.container) {
  1746. // If chartist was already initialized in this container we are detaching all event listeners first
  1747. if(this.container.__chartist__) {
  1748. this.container.__chartist__.detach();
  1749. }
  1750. this.container.__chartist__ = this;
  1751. }
  1752. // Using event loop for first draw to make it possible to register event listeners in the same call stack where
  1753. // the chart was created.
  1754. this.initializeTimeoutId = setTimeout(initialize.bind(this), 0);
  1755. }
  1756. // Creating the chart base class
  1757. Chartist.Base = Chartist.Class.extend({
  1758. constructor: Base,
  1759. optionsProvider: undefined,
  1760. container: undefined,
  1761. svg: undefined,
  1762. eventEmitter: undefined,
  1763. createChart: function() {
  1764. throw new Error('Base chart type can\'t be instantiated!');
  1765. },
  1766. update: update,
  1767. detach: detach,
  1768. on: on,
  1769. off: off,
  1770. version: Chartist.version,
  1771. supportsForeignObject: false
  1772. });
  1773. }(window, document, Chartist));
  1774. ;/**
  1775. * Chartist SVG module for simple SVG DOM abstraction
  1776. *
  1777. * @module Chartist.Svg
  1778. */
  1779. /* global Chartist */
  1780. (function(window, document, Chartist) {
  1781. 'use strict';
  1782. /**
  1783. * Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.
  1784. *
  1785. * @memberof Chartist.Svg
  1786. * @constructor
  1787. * @param {String|Element} name The name of the SVG element to create or an SVG dom element which should be wrapped into Chartist.Svg
  1788. * @param {Object} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
  1789. * @param {String} className This class or class list will be added to the SVG element
  1790. * @param {Object} parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child
  1791. * @param {Boolean} insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
  1792. */
  1793. function Svg(name, attributes, className, parent, insertFirst) {
  1794. // If Svg is getting called with an SVG element we just return the wrapper
  1795. if(name instanceof Element) {
  1796. this._node = name;
  1797. } else {
  1798. this._node = document.createElementNS(Chartist.namespaces.svg, name);
  1799. // If this is an SVG element created then custom namespace
  1800. if(name === 'svg') {
  1801. this.attr({
  1802. 'xmlns:ct': Chartist.namespaces.ct
  1803. });
  1804. }
  1805. }
  1806. if(attributes) {
  1807. this.attr(attributes);
  1808. }
  1809. if(className) {
  1810. this.addClass(className);
  1811. }
  1812. if(parent) {
  1813. if (insertFirst && parent._node.firstChild) {
  1814. parent._node.insertBefore(this._node, parent._node.firstChild);
  1815. } else {
  1816. parent._node.appendChild(this._node);
  1817. }
  1818. }
  1819. }
  1820. /**
  1821. * Set attributes on the current SVG element of the wrapper you're currently working on.
  1822. *
  1823. * @memberof Chartist.Svg
  1824. * @param {Object|String} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value.
  1825. * @param {String} [ns] If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object.
  1826. * @return {Object|String} The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function.
  1827. */
  1828. function attr(attributes, ns) {
  1829. if(typeof attributes === 'string') {
  1830. if(ns) {
  1831. return this._node.getAttributeNS(ns, attributes);
  1832. } else {
  1833. return this._node.getAttribute(attributes);
  1834. }
  1835. }
  1836. Object.keys(attributes).forEach(function(key) {
  1837. // If the attribute value is undefined we can skip this one
  1838. if(attributes[key] === undefined) {
  1839. return;
  1840. }
  1841. if (key.indexOf(':') !== -1) {
  1842. var namespacedAttribute = key.split(':');
  1843. this._node.setAttributeNS(Chartist.namespaces[namespacedAttribute[0]], key, attributes[key]);
  1844. } else {
  1845. this._node.setAttribute(key, attributes[key]);
  1846. }
  1847. }.bind(this));
  1848. return this;
  1849. }
  1850. /**
  1851. * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.
  1852. *
  1853. * @memberof Chartist.Svg
  1854. * @param {String} name The name of the SVG element that should be created as child element of the currently selected element wrapper
  1855. * @param {Object} [attributes] An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
  1856. * @param {String} [className] This class or class list will be added to the SVG element
  1857. * @param {Boolean} [insertFirst] If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
  1858. * @return {Chartist.Svg} Returns a Chartist.Svg wrapper object that can be used to modify the containing SVG data
  1859. */
  1860. function elem(name, attributes, className, insertFirst) {
  1861. return new Chartist.Svg(name, attributes, className, this, insertFirst);
  1862. }
  1863. /**
  1864. * Returns the parent Chartist.SVG wrapper object
  1865. *
  1866. * @memberof Chartist.Svg
  1867. * @return {Chartist.Svg} Returns a Chartist.Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null.
  1868. */
  1869. function parent() {
  1870. return this._node.parentNode instanceof SVGElement ? new Chartist.Svg(this._node.parentNode) : null;
  1871. }
  1872. /**
  1873. * This method returns a Chartist.Svg wrapper around the root SVG element of the current tree.
  1874. *
  1875. * @memberof Chartist.Svg
  1876. * @return {Chartist.Svg} The root SVG element wrapped in a Chartist.Svg element
  1877. */
  1878. function root() {
  1879. var node = this._node;
  1880. while(node.nodeName !== 'svg') {
  1881. node = node.parentNode;
  1882. }
  1883. return new Chartist.Svg(node);
  1884. }
  1885. /**
  1886. * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper.
  1887. *
  1888. * @memberof Chartist.Svg
  1889. * @param {String} selector A CSS selector that is used to query for child SVG elements
  1890. * @return {Chartist.Svg} The SVG wrapper for the element found or null if no element was found
  1891. */
  1892. function querySelector(selector) {
  1893. var foundNode = this._node.querySelector(selector);
  1894. return foundNode ? new Chartist.Svg(foundNode) : null;
  1895. }
  1896. /**
  1897. * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper.
  1898. *
  1899. * @memberof Chartist.Svg
  1900. * @param {String} selector A CSS selector that is used to query for child SVG elements
  1901. * @return {Chartist.Svg.List} The SVG wrapper list for the element found or null if no element was found
  1902. */
  1903. function querySelectorAll(selector) {
  1904. var foundNodes = this._node.querySelectorAll(selector);
  1905. return foundNodes.length ? new Chartist.Svg.List(foundNodes) : null;
  1906. }
  1907. /**
  1908. * Returns the underlying SVG node for the current element.
  1909. *
  1910. * @memberof Chartist.Svg
  1911. * @returns {Node}
  1912. */
  1913. function getNode() {
  1914. return this._node;
  1915. }
  1916. /**
  1917. * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.
  1918. *
  1919. * @memberof Chartist.Svg
  1920. * @param {Node|String} content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject
  1921. * @param {String} [attributes] An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added.
  1922. * @param {String} [className] This class or class list will be added to the SVG element
  1923. * @param {Boolean} [insertFirst] Specifies if the foreignObject should be inserted as first child
  1924. * @return {Chartist.Svg} New wrapper object that wraps the foreignObject element
  1925. */
  1926. function foreignObject(content, attributes, className, insertFirst) {
  1927. // If content is string then we convert it to DOM
  1928. // TODO: Handle case where content is not a string nor a DOM Node
  1929. if(typeof content === 'string') {
  1930. var container = document.createElement('div');
  1931. container.innerHTML = content;
  1932. content = container.firstChild;
  1933. }
  1934. // Adding namespace to content element
  1935. content.setAttribute('xmlns', Chartist.namespaces.xmlns);
  1936. // Creating the foreignObject without required extension attribute (as described here
  1937. // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)
  1938. var fnObj = this.elem('foreignObject', attributes, className, insertFirst);
  1939. // Add content to foreignObjectElement
  1940. fnObj._node.appendChild(content);
  1941. return fnObj;
  1942. }
  1943. /**
  1944. * This method adds a new text element to the current Chartist.Svg wrapper.
  1945. *
  1946. * @memberof Chartist.Svg
  1947. * @param {String} t The text that should be added to the text element that is created
  1948. * @return {Chartist.Svg} The same wrapper object that was used to add the newly created element
  1949. */
  1950. function text(t) {
  1951. this._node.appendChild(document.createTextNode(t));
  1952. return this;
  1953. }
  1954. /**
  1955. * This method will clear all child nodes of the current wrapper object.
  1956. *
  1957. * @memberof Chartist.Svg
  1958. * @return {Chartist.Svg} The same wrapper object that got emptied
  1959. */
  1960. function empty() {
  1961. while (this._node.firstChild) {
  1962. this._node.removeChild(this._node.firstChild);
  1963. }
  1964. return this;
  1965. }
  1966. /**
  1967. * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure.
  1968. *
  1969. * @memberof Chartist.Svg
  1970. * @return {Chartist.Svg} The parent wrapper object of the element that got removed
  1971. */
  1972. function remove() {
  1973. this._node.parentNode.removeChild(this._node);
  1974. return this.parent();
  1975. }
  1976. /**
  1977. * This method will replace the element with a new element that can be created outside of the current DOM.
  1978. *
  1979. * @memberof Chartist.Svg
  1980. * @param {Chartist.Svg} newElement The new Chartist.Svg object that will be used to replace the current wrapper object
  1981. * @return {Chartist.Svg} The wrapper of the new element
  1982. */
  1983. function replace(newElement) {
  1984. this._node.parentNode.replaceChild(newElement._node, this._node);
  1985. return newElement;
  1986. }
  1987. /**
  1988. * This method will append an element to the current element as a child.
  1989. *
  1990. * @memberof Chartist.Svg
  1991. * @param {Chartist.Svg} element The Chartist.Svg element that should be added as a child
  1992. * @param {Boolean} [insertFirst] Specifies if the element should be inserted as first child
  1993. * @return {Chartist.Svg} The wrapper of the appended object
  1994. */
  1995. function append(element, insertFirst) {
  1996. if(insertFirst && this._node.firstChild) {
  1997. this._node.insertBefore(element._node, this._node.firstChild);
  1998. } else {
  1999. this._node.appendChild(element._node);
  2000. }
  2001. return this;
  2002. }
  2003. /**
  2004. * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.
  2005. *
  2006. * @memberof Chartist.Svg
  2007. * @return {Array} A list of classes or an empty array if there are no classes on the current element
  2008. */
  2009. function classes() {
  2010. return this._node.getAttribute('class') ? this._node.getAttribute('class').trim().split(/\s+/) : [];
  2011. }
  2012. /**
  2013. * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.
  2014. *
  2015. * @memberof Chartist.Svg
  2016. * @param {String} names A white space separated list of class names
  2017. * @return {Chartist.Svg} The wrapper of the current element
  2018. */
  2019. function addClass(names) {
  2020. this._node.setAttribute('class',
  2021. this.classes(this._node)
  2022. .concat(names.trim().split(/\s+/))
  2023. .filter(function(elem, pos, self) {
  2024. return self.indexOf(elem) === pos;
  2025. }).join(' ')
  2026. );
  2027. return this;
  2028. }
  2029. /**
  2030. * Removes one or a space separated list of classes from the current element.
  2031. *
  2032. * @memberof Chartist.Svg
  2033. * @param {String} names A white space separated list of class names
  2034. * @return {Chartist.Svg} The wrapper of the current element
  2035. */
  2036. function removeClass(names) {
  2037. var removedClasses = names.trim().split(/\s+/);
  2038. this._node.setAttribute('class', this.classes(this._node).filter(function(name) {
  2039. return removedClasses.indexOf(name) === -1;
  2040. }).join(' '));
  2041. return this;
  2042. }
  2043. /**
  2044. * Removes all classes from the current element.
  2045. *
  2046. * @memberof Chartist.Svg
  2047. * @return {Chartist.Svg} The wrapper of the current element
  2048. */
  2049. function removeAllClasses() {
  2050. this._node.setAttribute('class', '');
  2051. return this;
  2052. }
  2053. /**
  2054. * Get element height using `getBoundingClientRect`
  2055. *
  2056. * @memberof Chartist.Svg
  2057. * @return {Number} The elements height in pixels
  2058. */
  2059. function height() {
  2060. return this._node.getBoundingClientRect().height;
  2061. }
  2062. /**
  2063. * Get element width using `getBoundingClientRect`
  2064. *
  2065. * @memberof Chartist.Core
  2066. * @return {Number} The elements width in pixels
  2067. */
  2068. function width() {
  2069. return this._node.getBoundingClientRect().width;
  2070. }
  2071. /**
  2072. * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in `Chartist.Svg.Easing` or an array with four numbers specifying a cubic Bézier curve.
  2073. * **An animations object could look like this:**
  2074. * ```javascript
  2075. * element.animate({
  2076. * opacity: {
  2077. * dur: 1000,
  2078. * from: 0,
  2079. * to: 1
  2080. * },
  2081. * x1: {
  2082. * dur: '1000ms',
  2083. * from: 100,
  2084. * to: 200,
  2085. * easing: 'easeOutQuart'
  2086. * },
  2087. * y1: {
  2088. * dur: '2s',
  2089. * from: 0,
  2090. * to: 100
  2091. * }
  2092. * });
  2093. * ```
  2094. * **Automatic unit conversion**
  2095. * For the `dur` and the `begin` animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds.
  2096. * **Guided mode**
  2097. * The default behavior of SMIL animations with offset using the `begin` attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation `from` value even before the animation starts. Also if you don't specify `fill="freeze"` on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the `begin` property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it.
  2098. * If guided mode is enabled the following behavior is added:
  2099. * - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation
  2100. * - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation)
  2101. * - The animate element will be forced to use `fill="freeze"`
  2102. * - The animation will be triggered with `beginElement()` in a timeout where `begin` of the definition object is interpreted in milli seconds. If no `begin` was specified the timeout is triggered immediately.
  2103. * - After the animation the element attribute value will be set to the `to` value of the animation
  2104. * - The animate element is deleted from the DOM
  2105. *
  2106. * @memberof Chartist.Svg
  2107. * @param {Object} animations An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode.
  2108. * @param {Boolean} guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated.
  2109. * @param {Object} eventEmitter If specified, this event emitter will be notified when an animation starts or ends.
  2110. * @return {Chartist.Svg} The current element where the animation was added
  2111. */
  2112. function animate(animations, guided, eventEmitter) {
  2113. if(guided === undefined) {
  2114. guided = true;
  2115. }
  2116. Object.keys(animations).forEach(function createAnimateForAttributes(attribute) {
  2117. function createAnimate(animationDefinition, guided) {
  2118. var attributeProperties = {},
  2119. animate,
  2120. timeout,
  2121. easing;
  2122. // Check if an easing is specified in the definition object and delete it from the object as it will not
  2123. // be part of the animate element attributes.
  2124. if(animationDefinition.easing) {
  2125. // If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object
  2126. easing = animationDefinition.easing instanceof Array ?
  2127. animationDefinition.easing :
  2128. Chartist.Svg.Easing[animationDefinition.easing];
  2129. delete animationDefinition.easing;
  2130. }
  2131. // If numeric dur or begin was provided we assume milli seconds
  2132. animationDefinition.begin = Chartist.ensureUnit(animationDefinition.begin, 'ms');
  2133. animationDefinition.dur = Chartist.ensureUnit(animationDefinition.dur, 'ms');
  2134. if(easing) {
  2135. animationDefinition.calcMode = 'spline';
  2136. animationDefinition.keySplines = easing.join(' ');
  2137. animationDefinition.keyTimes = '0;1';
  2138. }
  2139. // Adding "fill: freeze" if we are in guided mode and set initial attribute values
  2140. if(guided) {
  2141. animationDefinition.fill = 'freeze';
  2142. // Animated property on our element should already be set to the animation from value in guided mode
  2143. attributeProperties[attribute] = animationDefinition.from;
  2144. this.attr(attributeProperties);
  2145. // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin
  2146. // which needs to be in ms aside
  2147. timeout = Chartist.quantity(animationDefinition.begin || 0).value;
  2148. animationDefinition.begin = 'indefinite';
  2149. }
  2150. animate = this.elem('animate', Chartist.extend({
  2151. attributeName: attribute
  2152. }, animationDefinition));
  2153. if(guided) {
  2154. // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout
  2155. setTimeout(function() {
  2156. // If beginElement fails we set the animated attribute to the end position and remove the animate element
  2157. // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occured in
  2158. // the browser. (Currently FF 34 does not support animate elements in foreignObjects)
  2159. try {
  2160. animate._node.beginElement();
  2161. } catch(err) {
  2162. // Set animated attribute to current animated value
  2163. attributeProperties[attribute] = animationDefinition.to;
  2164. this.attr(attributeProperties);
  2165. // Remove the animate element as it's no longer required
  2166. animate.remove();
  2167. }
  2168. }.bind(this), timeout);
  2169. }
  2170. if(eventEmitter) {
  2171. animate._node.addEventListener('beginEvent', function handleBeginEvent() {
  2172. eventEmitter.emit('animationBegin', {
  2173. element: this,
  2174. animate: animate._node,
  2175. params: animationDefinition
  2176. });
  2177. }.bind(this));
  2178. }
  2179. animate._node.addEventListener('endEvent', function handleEndEvent() {
  2180. if(eventEmitter) {
  2181. eventEmitter.emit('animationEnd', {
  2182. element: this,
  2183. animate: animate._node,
  2184. params: animationDefinition
  2185. });
  2186. }
  2187. if(guided) {
  2188. // Set animated attribute to current animated value
  2189. attributeProperties[attribute] = animationDefinition.to;
  2190. this.attr(attributeProperties);
  2191. // Remove the animate element as it's no longer required
  2192. animate.remove();
  2193. }
  2194. }.bind(this));
  2195. }
  2196. // If current attribute is an array of definition objects we create an animate for each and disable guided mode
  2197. if(animations[attribute] instanceof Array) {
  2198. animations[attribute].forEach(function(animationDefinition) {
  2199. createAnimate.bind(this)(animationDefinition, false);
  2200. }.bind(this));
  2201. } else {
  2202. createAnimate.bind(this)(animations[attribute], guided);
  2203. }
  2204. }.bind(this));
  2205. return this;
  2206. }
  2207. Chartist.Svg = Chartist.Class.extend({
  2208. constructor: Svg,
  2209. attr: attr,
  2210. elem: elem,
  2211. parent: parent,
  2212. root: root,
  2213. querySelector: querySelector,
  2214. querySelectorAll: querySelectorAll,
  2215. getNode: getNode,
  2216. foreignObject: foreignObject,
  2217. text: text,
  2218. empty: empty,
  2219. remove: remove,
  2220. replace: replace,
  2221. append: append,
  2222. classes: classes,
  2223. addClass: addClass,
  2224. removeClass: removeClass,
  2225. removeAllClasses: removeAllClasses,
  2226. height: height,
  2227. width: width,
  2228. animate: animate
  2229. });
  2230. /**
  2231. * This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list.
  2232. *
  2233. * @memberof Chartist.Svg
  2234. * @param {String} feature The SVG 1.1 feature that should be checked for support.
  2235. * @return {Boolean} True of false if the feature is supported or not
  2236. */
  2237. Chartist.Svg.isSupported = function(feature) {
  2238. return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#' + feature, '1.1');
  2239. };
  2240. /**
  2241. * This Object contains some standard easing cubic bezier curves. Then can be used with their name in the `Chartist.Svg.animate`. You can also extend the list and use your own name in the `animate` function. Click the show code button to see the available bezier functions.
  2242. *
  2243. * @memberof Chartist.Svg
  2244. */
  2245. var easingCubicBeziers = {
  2246. easeInSine: [0.47, 0, 0.745, 0.715],
  2247. easeOutSine: [0.39, 0.575, 0.565, 1],
  2248. easeInOutSine: [0.445, 0.05, 0.55, 0.95],
  2249. easeInQuad: [0.55, 0.085, 0.68, 0.53],
  2250. easeOutQuad: [0.25, 0.46, 0.45, 0.94],
  2251. easeInOutQuad: [0.455, 0.03, 0.515, 0.955],
  2252. easeInCubic: [0.55, 0.055, 0.675, 0.19],
  2253. easeOutCubic: [0.215, 0.61, 0.355, 1],
  2254. easeInOutCubic: [0.645, 0.045, 0.355, 1],
  2255. easeInQuart: [0.895, 0.03, 0.685, 0.22],
  2256. easeOutQuart: [0.165, 0.84, 0.44, 1],
  2257. easeInOutQuart: [0.77, 0, 0.175, 1],
  2258. easeInQuint: [0.755, 0.05, 0.855, 0.06],
  2259. easeOutQuint: [0.23, 1, 0.32, 1],
  2260. easeInOutQuint: [0.86, 0, 0.07, 1],
  2261. easeInExpo: [0.95, 0.05, 0.795, 0.035],
  2262. easeOutExpo: [0.19, 1, 0.22, 1],
  2263. easeInOutExpo: [1, 0, 0, 1],
  2264. easeInCirc: [0.6, 0.04, 0.98, 0.335],
  2265. easeOutCirc: [0.075, 0.82, 0.165, 1],
  2266. easeInOutCirc: [0.785, 0.135, 0.15, 0.86],
  2267. easeInBack: [0.6, -0.28, 0.735, 0.045],
  2268. easeOutBack: [0.175, 0.885, 0.32, 1.275],
  2269. easeInOutBack: [0.68, -0.55, 0.265, 1.55]
  2270. };
  2271. Chartist.Svg.Easing = easingCubicBeziers;
  2272. /**
  2273. * This helper class is to wrap multiple `Chartist.Svg` elements into a list where you can call the `Chartist.Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Chartist.Svg` on multiple elements.
  2274. * An instance of this class is also returned by `Chartist.Svg.querySelectorAll`.
  2275. *
  2276. * @memberof Chartist.Svg
  2277. * @param {Array<Node>|NodeList} nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)
  2278. * @constructor
  2279. */
  2280. function SvgList(nodeList) {
  2281. var list = this;
  2282. this.svgElements = [];
  2283. for(var i = 0; i < nodeList.length; i++) {
  2284. this.svgElements.push(new Chartist.Svg(nodeList[i]));
  2285. }
  2286. // Add delegation methods for Chartist.Svg
  2287. Object.keys(Chartist.Svg.prototype).filter(function(prototypeProperty) {
  2288. return ['constructor',
  2289. 'parent',
  2290. 'querySelector',
  2291. 'querySelectorAll',
  2292. 'replace',
  2293. 'append',
  2294. 'classes',
  2295. 'height',
  2296. 'width'].indexOf(prototypeProperty) === -1;
  2297. }).forEach(function(prototypeProperty) {
  2298. list[prototypeProperty] = function() {
  2299. var args = Array.prototype.slice.call(arguments, 0);
  2300. list.svgElements.forEach(function(element) {
  2301. Chartist.Svg.prototype[prototypeProperty].apply(element, args);
  2302. });
  2303. return list;
  2304. };
  2305. });
  2306. }
  2307. Chartist.Svg.List = Chartist.Class.extend({
  2308. constructor: SvgList
  2309. });
  2310. }(window, document, Chartist));
  2311. ;/**
  2312. * Chartist SVG path module for SVG path description creation and modification.
  2313. *
  2314. * @module Chartist.Svg.Path
  2315. */
  2316. /* global Chartist */
  2317. (function(window, document, Chartist) {
  2318. 'use strict';
  2319. /**
  2320. * Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.
  2321. *
  2322. * @memberof Chartist.Svg.Path
  2323. * @type {Object}
  2324. */
  2325. var elementDescriptions = {
  2326. m: ['x', 'y'],
  2327. l: ['x', 'y'],
  2328. c: ['x1', 'y1', 'x2', 'y2', 'x', 'y'],
  2329. a: ['rx', 'ry', 'xAr', 'lAf', 'sf', 'x', 'y']
  2330. };
  2331. /**
  2332. * Default options for newly created SVG path objects.
  2333. *
  2334. * @memberof Chartist.Svg.Path
  2335. * @type {Object}
  2336. */
  2337. var defaultOptions = {
  2338. // The accuracy in digit count after the decimal point. This will be used to round numbers in the SVG path. If this option is set to false then no rounding will be performed.
  2339. accuracy: 3
  2340. };
  2341. function element(command, params, pathElements, pos, relative, data) {
  2342. var pathElement = Chartist.extend({
  2343. command: relative ? command.toLowerCase() : command.toUpperCase()
  2344. }, params, data ? { data: data } : {} );
  2345. pathElements.splice(pos, 0, pathElement);
  2346. }
  2347. function forEachParam(pathElements, cb) {
  2348. pathElements.forEach(function(pathElement, pathElementIndex) {
  2349. elementDescriptions[pathElement.command.toLowerCase()].forEach(function(paramName, paramIndex) {
  2350. cb(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
  2351. });
  2352. });
  2353. }
  2354. /**
  2355. * Used to construct a new path object.
  2356. *
  2357. * @memberof Chartist.Svg.Path
  2358. * @param {Boolean} close If set to true then this path will be closed when stringified (with a Z at the end)
  2359. * @param {Object} options Options object that overrides the default objects. See default options for more details.
  2360. * @constructor
  2361. */
  2362. function SvgPath(close, options) {
  2363. this.pathElements = [];
  2364. this.pos = 0;
  2365. this.close = close;
  2366. this.options = Chartist.extend({}, defaultOptions, options);
  2367. }
  2368. /**
  2369. * Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.
  2370. *
  2371. * @memberof Chartist.Svg.Path
  2372. * @param {Number} [pos] If a number is passed then the cursor is set to this position in the path element array.
  2373. * @return {Chartist.Svg.Path|Number} If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned.
  2374. */
  2375. function position(pos) {
  2376. if(pos !== undefined) {
  2377. this.pos = Math.max(0, Math.min(this.pathElements.length, pos));
  2378. return this;
  2379. } else {
  2380. return this.pos;
  2381. }
  2382. }
  2383. /**
  2384. * Removes elements from the path starting at the current position.
  2385. *
  2386. * @memberof Chartist.Svg.Path
  2387. * @param {Number} count Number of path elements that should be removed from the current position.
  2388. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2389. */
  2390. function remove(count) {
  2391. this.pathElements.splice(this.pos, count);
  2392. return this;
  2393. }
  2394. /**
  2395. * Use this function to add a new move SVG path element.
  2396. *
  2397. * @memberof Chartist.Svg.Path
  2398. * @param {Number} x The x coordinate for the move element.
  2399. * @param {Number} y The y coordinate for the move element.
  2400. * @param {Boolean} [relative] If set to true the move element will be created with relative coordinates (lowercase letter)
  2401. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2402. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2403. */
  2404. function move(x, y, relative, data) {
  2405. element('M', {
  2406. x: +x,
  2407. y: +y
  2408. }, this.pathElements, this.pos++, relative, data);
  2409. return this;
  2410. }
  2411. /**
  2412. * Use this function to add a new line SVG path element.
  2413. *
  2414. * @memberof Chartist.Svg.Path
  2415. * @param {Number} x The x coordinate for the line element.
  2416. * @param {Number} y The y coordinate for the line element.
  2417. * @param {Boolean} [relative] If set to true the line element will be created with relative coordinates (lowercase letter)
  2418. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2419. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2420. */
  2421. function line(x, y, relative, data) {
  2422. element('L', {
  2423. x: +x,
  2424. y: +y
  2425. }, this.pathElements, this.pos++, relative, data);
  2426. return this;
  2427. }
  2428. /**
  2429. * Use this function to add a new curve SVG path element.
  2430. *
  2431. * @memberof Chartist.Svg.Path
  2432. * @param {Number} x1 The x coordinate for the first control point of the bezier curve.
  2433. * @param {Number} y1 The y coordinate for the first control point of the bezier curve.
  2434. * @param {Number} x2 The x coordinate for the second control point of the bezier curve.
  2435. * @param {Number} y2 The y coordinate for the second control point of the bezier curve.
  2436. * @param {Number} x The x coordinate for the target point of the curve element.
  2437. * @param {Number} y The y coordinate for the target point of the curve element.
  2438. * @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
  2439. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2440. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2441. */
  2442. function curve(x1, y1, x2, y2, x, y, relative, data) {
  2443. element('C', {
  2444. x1: +x1,
  2445. y1: +y1,
  2446. x2: +x2,
  2447. y2: +y2,
  2448. x: +x,
  2449. y: +y
  2450. }, this.pathElements, this.pos++, relative, data);
  2451. return this;
  2452. }
  2453. /**
  2454. * Use this function to add a new non-bezier curve SVG path element.
  2455. *
  2456. * @memberof Chartist.Svg.Path
  2457. * @param {Number} rx The radius to be used for the x-axis of the arc.
  2458. * @param {Number} ry The radius to be used for the y-axis of the arc.
  2459. * @param {Number} xAr Defines the orientation of the arc
  2460. * @param {Number} lAf Large arc flag
  2461. * @param {Number} sf Sweep flag
  2462. * @param {Number} x The x coordinate for the target point of the curve element.
  2463. * @param {Number} y The y coordinate for the target point of the curve element.
  2464. * @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
  2465. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2466. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2467. */
  2468. function arc(rx, ry, xAr, lAf, sf, x, y, relative, data) {
  2469. element('A', {
  2470. rx: +rx,
  2471. ry: +ry,
  2472. xAr: +xAr,
  2473. lAf: +lAf,
  2474. sf: +sf,
  2475. x: +x,
  2476. y: +y
  2477. }, this.pathElements, this.pos++, relative, data);
  2478. return this;
  2479. }
  2480. /**
  2481. * Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object.
  2482. *
  2483. * @memberof Chartist.Svg.Path
  2484. * @param {String} path Any SVG path that contains move (m), line (l) or curve (c) components.
  2485. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2486. */
  2487. function parse(path) {
  2488. // Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']]
  2489. var chunks = path.replace(/([A-Za-z])([0-9])/g, '$1 $2')
  2490. .replace(/([0-9])([A-Za-z])/g, '$1 $2')
  2491. .split(/[\s,]+/)
  2492. .reduce(function(result, element) {
  2493. if(element.match(/[A-Za-z]/)) {
  2494. result.push([]);
  2495. }
  2496. result[result.length - 1].push(element);
  2497. return result;
  2498. }, []);
  2499. // If this is a closed path we remove the Z at the end because this is determined by the close option
  2500. if(chunks[chunks.length - 1][0].toUpperCase() === 'Z') {
  2501. chunks.pop();
  2502. }
  2503. // Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters
  2504. // For example {command: 'M', x: '10', y: '10'}
  2505. var elements = chunks.map(function(chunk) {
  2506. var command = chunk.shift(),
  2507. description = elementDescriptions[command.toLowerCase()];
  2508. return Chartist.extend({
  2509. command: command
  2510. }, description.reduce(function(result, paramName, index) {
  2511. result[paramName] = +chunk[index];
  2512. return result;
  2513. }, {}));
  2514. });
  2515. // Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position
  2516. var spliceArgs = [this.pos, 0];
  2517. Array.prototype.push.apply(spliceArgs, elements);
  2518. Array.prototype.splice.apply(this.pathElements, spliceArgs);
  2519. // Increase the internal position by the element count
  2520. this.pos += elements.length;
  2521. return this;
  2522. }
  2523. /**
  2524. * This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string.
  2525. *
  2526. * @memberof Chartist.Svg.Path
  2527. * @return {String}
  2528. */
  2529. function stringify() {
  2530. var accuracyMultiplier = Math.pow(10, this.options.accuracy);
  2531. return this.pathElements.reduce(function(path, pathElement) {
  2532. var params = elementDescriptions[pathElement.command.toLowerCase()].map(function(paramName) {
  2533. return this.options.accuracy ?
  2534. (Math.round(pathElement[paramName] * accuracyMultiplier) / accuracyMultiplier) :
  2535. pathElement[paramName];
  2536. }.bind(this));
  2537. return path + pathElement.command + params.join(',');
  2538. }.bind(this), '') + (this.close ? 'Z' : '');
  2539. }
  2540. /**
  2541. * Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate.
  2542. *
  2543. * @memberof Chartist.Svg.Path
  2544. * @param {Number} x The number which will be used to scale the x, x1 and x2 of all path elements.
  2545. * @param {Number} y The number which will be used to scale the y, y1 and y2 of all path elements.
  2546. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2547. */
  2548. function scale(x, y) {
  2549. forEachParam(this.pathElements, function(pathElement, paramName) {
  2550. pathElement[paramName] *= paramName[0] === 'x' ? x : y;
  2551. });
  2552. return this;
  2553. }
  2554. /**
  2555. * Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate.
  2556. *
  2557. * @memberof Chartist.Svg.Path
  2558. * @param {Number} x The number which will be used to translate the x, x1 and x2 of all path elements.
  2559. * @param {Number} y The number which will be used to translate the y, y1 and y2 of all path elements.
  2560. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2561. */
  2562. function translate(x, y) {
  2563. forEachParam(this.pathElements, function(pathElement, paramName) {
  2564. pathElement[paramName] += paramName[0] === 'x' ? x : y;
  2565. });
  2566. return this;
  2567. }
  2568. /**
  2569. * This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.
  2570. * The method signature of the callback function looks like this:
  2571. * ```javascript
  2572. * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)
  2573. * ```
  2574. * If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.
  2575. *
  2576. * @memberof Chartist.Svg.Path
  2577. * @param {Function} transformFnc The callback function for the transformation. Check the signature in the function description.
  2578. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2579. */
  2580. function transform(transformFnc) {
  2581. forEachParam(this.pathElements, function(pathElement, paramName, pathElementIndex, paramIndex, pathElements) {
  2582. var transformed = transformFnc(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
  2583. if(transformed || transformed === 0) {
  2584. pathElement[paramName] = transformed;
  2585. }
  2586. });
  2587. return this;
  2588. }
  2589. /**
  2590. * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.
  2591. *
  2592. * @memberof Chartist.Svg.Path
  2593. * @param {Boolean} [close] Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.
  2594. * @return {Chartist.Svg.Path}
  2595. */
  2596. function clone(close) {
  2597. var c = new Chartist.Svg.Path(close || this.close);
  2598. c.pos = this.pos;
  2599. c.pathElements = this.pathElements.slice().map(function cloneElements(pathElement) {
  2600. return Chartist.extend({}, pathElement);
  2601. });
  2602. c.options = Chartist.extend({}, this.options);
  2603. return c;
  2604. }
  2605. /**
  2606. * Split a Svg.Path object by a specific command in the path chain. The path chain will be split and an array of newly created paths objects will be returned. This is useful if you'd like to split an SVG path by it's move commands, for example, in order to isolate chunks of drawings.
  2607. *
  2608. * @memberof Chartist.Svg.Path
  2609. * @param {String} command The command you'd like to use to split the path
  2610. * @return {Array<Chartist.Svg.Path>}
  2611. */
  2612. function splitByCommand(command) {
  2613. var split = [
  2614. new Chartist.Svg.Path()
  2615. ];
  2616. this.pathElements.forEach(function(pathElement) {
  2617. if(pathElement.command === command.toUpperCase() && split[split.length - 1].pathElements.length !== 0) {
  2618. split.push(new Chartist.Svg.Path());
  2619. }
  2620. split[split.length - 1].pathElements.push(pathElement);
  2621. });
  2622. return split;
  2623. }
  2624. /**
  2625. * This static function on `Chartist.Svg.Path` is joining multiple paths together into one paths.
  2626. *
  2627. * @memberof Chartist.Svg.Path
  2628. * @param {Array<Chartist.Svg.Path>} paths A list of paths to be joined together. The order is important.
  2629. * @param {boolean} close If the newly created path should be a closed path
  2630. * @param {Object} options Path options for the newly created path.
  2631. * @return {Chartist.Svg.Path}
  2632. */
  2633. function join(paths, close, options) {
  2634. var joinedPath = new Chartist.Svg.Path(close, options);
  2635. for(var i = 0; i < paths.length; i++) {
  2636. var path = paths[i];
  2637. for(var j = 0; j < path.pathElements.length; j++) {
  2638. joinedPath.pathElements.push(path.pathElements[j]);
  2639. }
  2640. }
  2641. return joinedPath;
  2642. }
  2643. Chartist.Svg.Path = Chartist.Class.extend({
  2644. constructor: SvgPath,
  2645. position: position,
  2646. remove: remove,
  2647. move: move,
  2648. line: line,
  2649. curve: curve,
  2650. arc: arc,
  2651. scale: scale,
  2652. translate: translate,
  2653. transform: transform,
  2654. parse: parse,
  2655. stringify: stringify,
  2656. clone: clone,
  2657. splitByCommand: splitByCommand
  2658. });
  2659. Chartist.Svg.Path.elementDescriptions = elementDescriptions;
  2660. Chartist.Svg.Path.join = join;
  2661. }(window, document, Chartist));
  2662. ;/* global Chartist */
  2663. (function (window, document, Chartist) {
  2664. 'use strict';
  2665. var axisUnits = {
  2666. x: {
  2667. pos: 'x',
  2668. len: 'width',
  2669. dir: 'horizontal',
  2670. rectStart: 'x1',
  2671. rectEnd: 'x2',
  2672. rectOffset: 'y2'
  2673. },
  2674. y: {
  2675. pos: 'y',
  2676. len: 'height',
  2677. dir: 'vertical',
  2678. rectStart: 'y2',
  2679. rectEnd: 'y1',
  2680. rectOffset: 'x1'
  2681. }
  2682. };
  2683. function Axis(units, chartRect, ticks, options) {
  2684. this.units = units;
  2685. this.counterUnits = units === axisUnits.x ? axisUnits.y : axisUnits.x;
  2686. this.chartRect = chartRect;
  2687. this.axisLength = chartRect[units.rectEnd] - chartRect[units.rectStart];
  2688. this.gridOffset = chartRect[units.rectOffset];
  2689. this.ticks = ticks;
  2690. this.options = options;
  2691. }
  2692. function createGridAndLabels(gridGroup, labelGroup, useForeignObject, chartOptions, eventEmitter) {
  2693. var axisOptions = chartOptions['axis' + this.units.pos.toUpperCase()];
  2694. var projectedValues = this.ticks.map(this.projectValue.bind(this));
  2695. var labelValues = this.ticks.map(axisOptions.labelInterpolationFnc);
  2696. projectedValues.forEach(function(projectedValue, index) {
  2697. var labelOffset = {
  2698. x: 0,
  2699. y: 0
  2700. };
  2701. // TODO: Find better solution for solving this problem
  2702. // Calculate how much space we have available for the label
  2703. var labelLength;
  2704. if(projectedValues[index + 1]) {
  2705. // If we still have one label ahead, we can calculate the distance to the next tick / label
  2706. labelLength = projectedValues[index + 1] - projectedValue;
  2707. } else {
  2708. // If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to
  2709. // on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will
  2710. // still be visible inside of the chart padding.
  2711. labelLength = Math.max(this.axisLength - projectedValue, 30);
  2712. }
  2713. // Skip grid lines and labels where interpolated label values are falsey (execpt for 0)
  2714. if(Chartist.isFalseyButZero(labelValues[index]) && labelValues[index] !== '') {
  2715. return;
  2716. }
  2717. // Transform to global coordinates using the chartRect
  2718. // We also need to set the label offset for the createLabel function
  2719. if(this.units.pos === 'x') {
  2720. projectedValue = this.chartRect.x1 + projectedValue;
  2721. labelOffset.x = chartOptions.axisX.labelOffset.x;
  2722. // If the labels should be positioned in start position (top side for vertical axis) we need to set a
  2723. // different offset as for positioned with end (bottom)
  2724. if(chartOptions.axisX.position === 'start') {
  2725. labelOffset.y = this.chartRect.padding.top + chartOptions.axisX.labelOffset.y + (useForeignObject ? 5 : 20);
  2726. } else {
  2727. labelOffset.y = this.chartRect.y1 + chartOptions.axisX.labelOffset.y + (useForeignObject ? 5 : 20);
  2728. }
  2729. } else {
  2730. projectedValue = this.chartRect.y1 - projectedValue;
  2731. labelOffset.y = chartOptions.axisY.labelOffset.y - (useForeignObject ? labelLength : 0);
  2732. // If the labels should be positioned in start position (left side for horizontal axis) we need to set a
  2733. // different offset as for positioned with end (right side)
  2734. if(chartOptions.axisY.position === 'start') {
  2735. labelOffset.x = useForeignObject ? this.chartRect.padding.left + chartOptions.axisY.labelOffset.x : this.chartRect.x1 - 10;
  2736. } else {
  2737. labelOffset.x = this.chartRect.x2 + chartOptions.axisY.labelOffset.x + 10;
  2738. }
  2739. }
  2740. if(axisOptions.showGrid) {
  2741. Chartist.createGrid(projectedValue, index, this, this.gridOffset, this.chartRect[this.counterUnits.len](), gridGroup, [
  2742. chartOptions.classNames.grid,
  2743. chartOptions.classNames[this.units.dir]
  2744. ], eventEmitter);
  2745. }
  2746. if(axisOptions.showLabel) {
  2747. Chartist.createLabel(projectedValue, labelLength, index, labelValues, this, axisOptions.offset, labelOffset, labelGroup, [
  2748. chartOptions.classNames.label,
  2749. chartOptions.classNames[this.units.dir],
  2750. (axisOptions.position === 'start' ? chartOptions.classNames[axisOptions.position] : chartOptions.classNames['end'])
  2751. ], useForeignObject, eventEmitter);
  2752. }
  2753. }.bind(this));
  2754. }
  2755. Chartist.Axis = Chartist.Class.extend({
  2756. constructor: Axis,
  2757. createGridAndLabels: createGridAndLabels,
  2758. projectValue: function(value, index, data) {
  2759. throw new Error('Base axis can\'t be instantiated!');
  2760. }
  2761. });
  2762. Chartist.Axis.units = axisUnits;
  2763. }(window, document, Chartist));
  2764. ;/**
  2765. * The auto scale axis uses standard linear scale projection of values along an axis. It uses order of magnitude to find a scale automatically and evaluates the available space in order to find the perfect amount of ticks for your chart.
  2766. * **Options**
  2767. * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
  2768. * ```javascript
  2769. * var options = {
  2770. * // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
  2771. * high: 100,
  2772. * // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
  2773. * low: 0,
  2774. * // This option will be used when finding the right scale division settings. The amount of ticks on the scale will be determined so that as many ticks as possible will be displayed, while not violating this minimum required space (in pixel).
  2775. * scaleMinSpace: 20,
  2776. * // Can be set to true or false. If set to true, the scale will be generated with whole numbers only.
  2777. * onlyInteger: true,
  2778. * // The reference value can be used to make sure that this value will always be on the chart. This is especially useful on bipolar charts where the bipolar center always needs to be part of the chart.
  2779. * referenceValue: 5
  2780. * };
  2781. * ```
  2782. *
  2783. * @module Chartist.AutoScaleAxis
  2784. */
  2785. /* global Chartist */
  2786. (function (window, document, Chartist) {
  2787. 'use strict';
  2788. function AutoScaleAxis(axisUnit, data, chartRect, options) {
  2789. // Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options
  2790. var highLow = options.highLow || Chartist.getHighLow(data, options, axisUnit.pos);
  2791. this.bounds = Chartist.getBounds(chartRect[axisUnit.rectEnd] - chartRect[axisUnit.rectStart], highLow, options.scaleMinSpace || 20, options.onlyInteger);
  2792. this.range = {
  2793. min: this.bounds.min,
  2794. max: this.bounds.max
  2795. };
  2796. Chartist.AutoScaleAxis.super.constructor.call(this,
  2797. axisUnit,
  2798. chartRect,
  2799. this.bounds.values,
  2800. options);
  2801. }
  2802. function projectValue(value) {
  2803. return this.axisLength * (+Chartist.getMultiValue(value, this.units.pos) - this.bounds.min) / this.bounds.range;
  2804. }
  2805. Chartist.AutoScaleAxis = Chartist.Axis.extend({
  2806. constructor: AutoScaleAxis,
  2807. projectValue: projectValue
  2808. });
  2809. }(window, document, Chartist));
  2810. ;/**
  2811. * The fixed scale axis uses standard linear projection of values along an axis. It makes use of a divisor option to divide the range provided from the minimum and maximum value or the options high and low that will override the computed minimum and maximum.
  2812. * **Options**
  2813. * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
  2814. * ```javascript
  2815. * var options = {
  2816. * // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
  2817. * high: 100,
  2818. * // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
  2819. * low: 0,
  2820. * // If specified then the value range determined from minimum to maximum (or low and high) will be divided by this number and ticks will be generated at those division points. The default divisor is 1.
  2821. * divisor: 4,
  2822. * // If ticks is explicitly set, then the axis will not compute the ticks with the divisor, but directly use the data in ticks to determine at what points on the axis a tick need to be generated.
  2823. * ticks: [1, 10, 20, 30]
  2824. * };
  2825. * ```
  2826. *
  2827. * @module Chartist.FixedScaleAxis
  2828. */
  2829. /* global Chartist */
  2830. (function (window, document, Chartist) {
  2831. 'use strict';
  2832. function FixedScaleAxis(axisUnit, data, chartRect, options) {
  2833. var highLow = options.highLow || Chartist.getHighLow(data, options, axisUnit.pos);
  2834. this.divisor = options.divisor || 1;
  2835. this.ticks = options.ticks || Chartist.times(this.divisor).map(function(value, index) {
  2836. return highLow.low + (highLow.high - highLow.low) / this.divisor * index;
  2837. }.bind(this));
  2838. this.ticks.sort(function(a, b) {
  2839. return a - b;
  2840. });
  2841. this.range = {
  2842. min: highLow.low,
  2843. max: highLow.high
  2844. };
  2845. Chartist.FixedScaleAxis.super.constructor.call(this,
  2846. axisUnit,
  2847. chartRect,
  2848. this.ticks,
  2849. options);
  2850. this.stepLength = this.axisLength / this.divisor;
  2851. }
  2852. function projectValue(value) {
  2853. return this.axisLength * (+Chartist.getMultiValue(value, this.units.pos) - this.range.min) / (this.range.max - this.range.min);
  2854. }
  2855. Chartist.FixedScaleAxis = Chartist.Axis.extend({
  2856. constructor: FixedScaleAxis,
  2857. projectValue: projectValue
  2858. });
  2859. }(window, document, Chartist));
  2860. ;/**
  2861. * The step axis for step based charts like bar chart or step based line charts. It uses a fixed amount of ticks that will be equally distributed across the whole axis length. The projection is done using the index of the data value rather than the value itself and therefore it's only useful for distribution purpose.
  2862. * **Options**
  2863. * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
  2864. * ```javascript
  2865. * var options = {
  2866. * // Ticks to be used to distribute across the axis length. As this axis type relies on the index of the value rather than the value, arbitrary data that can be converted to a string can be used as ticks.
  2867. * ticks: ['One', 'Two', 'Three'],
  2868. * // If set to true the full width will be used to distribute the values where the last value will be at the maximum of the axis length. If false the spaces between the ticks will be evenly distributed instead.
  2869. * stretch: true
  2870. * };
  2871. * ```
  2872. *
  2873. * @module Chartist.StepAxis
  2874. */
  2875. /* global Chartist */
  2876. (function (window, document, Chartist) {
  2877. 'use strict';
  2878. function StepAxis(axisUnit, data, chartRect, options) {
  2879. Chartist.StepAxis.super.constructor.call(this,
  2880. axisUnit,
  2881. chartRect,
  2882. options.ticks,
  2883. options);
  2884. var calc = Math.max(1, options.ticks.length - (options.stretch ? 1 : 0));
  2885. this.stepLength = this.axisLength / calc;
  2886. }
  2887. function projectValue(value, index) {
  2888. return this.stepLength * index;
  2889. }
  2890. Chartist.StepAxis = Chartist.Axis.extend({
  2891. constructor: StepAxis,
  2892. projectValue: projectValue
  2893. });
  2894. }(window, document, Chartist));
  2895. ;/**
  2896. * The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global `Chartist` namespace where you find the `Line` function as a main entry point.
  2897. *
  2898. * For examples on how to use the line chart please check the examples of the `Chartist.Line` method.
  2899. *
  2900. * @module Chartist.Line
  2901. */
  2902. /* global Chartist */
  2903. (function(window, document, Chartist){
  2904. 'use strict';
  2905. /**
  2906. * Default options in line charts. Expand the code view to see a detailed list of options with comments.
  2907. *
  2908. * @memberof Chartist.Line
  2909. */
  2910. var defaultOptions = {
  2911. // Options for X-Axis
  2912. axisX: {
  2913. // The offset of the labels to the chart area
  2914. offset: 30,
  2915. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  2916. position: 'end',
  2917. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  2918. labelOffset: {
  2919. x: 0,
  2920. y: 0
  2921. },
  2922. // If labels should be shown or not
  2923. showLabel: true,
  2924. // If the axis grid should be drawn or not
  2925. showGrid: true,
  2926. // Interpolation function that allows you to intercept the value from the axis label
  2927. labelInterpolationFnc: Chartist.noop,
  2928. // Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
  2929. type: undefined
  2930. },
  2931. // Options for Y-Axis
  2932. axisY: {
  2933. // The offset of the labels to the chart area
  2934. offset: 40,
  2935. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  2936. position: 'start',
  2937. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  2938. labelOffset: {
  2939. x: 0,
  2940. y: 0
  2941. },
  2942. // If labels should be shown or not
  2943. showLabel: true,
  2944. // If the axis grid should be drawn or not
  2945. showGrid: true,
  2946. // Interpolation function that allows you to intercept the value from the axis label
  2947. labelInterpolationFnc: Chartist.noop,
  2948. // Set the axis type to be used to project values on this axis. If not defined, Chartist.AutoScaleAxis will be used for the Y-Axis, where the high and low options will be set to the global high and low options. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
  2949. type: undefined,
  2950. // This value specifies the minimum height in pixel of the scale steps
  2951. scaleMinSpace: 20,
  2952. // Use only integer values (whole numbers) for the scale steps
  2953. onlyInteger: false
  2954. },
  2955. // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
  2956. width: undefined,
  2957. // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
  2958. height: undefined,
  2959. // If the line should be drawn or not
  2960. showLine: true,
  2961. // If dots should be drawn or not
  2962. showPoint: true,
  2963. // If the line chart should draw an area
  2964. showArea: false,
  2965. // The base for the area chart that will be used to close the area shape (is normally 0)
  2966. areaBase: 0,
  2967. // Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description.
  2968. lineSmooth: true,
  2969. // If the line chart should add a background fill to the .ct-grids group.
  2970. showGridBackground: false,
  2971. // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
  2972. low: undefined,
  2973. // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
  2974. high: undefined,
  2975. // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
  2976. chartPadding: {
  2977. top: 15,
  2978. right: 15,
  2979. bottom: 5,
  2980. left: 10
  2981. },
  2982. // When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler.
  2983. fullWidth: false,
  2984. // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
  2985. reverseData: false,
  2986. // Override the class names that get used to generate the SVG structure of the chart
  2987. classNames: {
  2988. chart: 'ct-chart-line',
  2989. label: 'ct-label',
  2990. labelGroup: 'ct-labels',
  2991. series: 'ct-series',
  2992. line: 'ct-line',
  2993. point: 'ct-point',
  2994. area: 'ct-area',
  2995. grid: 'ct-grid',
  2996. gridGroup: 'ct-grids',
  2997. gridBackground: 'ct-grid-background',
  2998. vertical: 'ct-vertical',
  2999. horizontal: 'ct-horizontal',
  3000. start: 'ct-start',
  3001. end: 'ct-end'
  3002. }
  3003. };
  3004. /**
  3005. * Creates a new chart
  3006. *
  3007. */
  3008. function createChart(options) {
  3009. var data = Chartist.normalizeData(this.data, options.reverseData, true);
  3010. // Create new svg object
  3011. this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);
  3012. // Create groups for labels, grid and series
  3013. var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);
  3014. var seriesGroup = this.svg.elem('g');
  3015. var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);
  3016. var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
  3017. var axisX, axisY;
  3018. if(options.axisX.type === undefined) {
  3019. axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
  3020. ticks: data.normalized.labels,
  3021. stretch: options.fullWidth
  3022. }));
  3023. } else {
  3024. axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);
  3025. }
  3026. if(options.axisY.type === undefined) {
  3027. axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
  3028. high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,
  3029. low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low
  3030. }));
  3031. } else {
  3032. axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);
  3033. }
  3034. axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3035. axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3036. if (options.showGridBackground) {
  3037. Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
  3038. }
  3039. // Draw the series
  3040. data.raw.series.forEach(function(series, seriesIndex) {
  3041. var seriesElement = seriesGroup.elem('g');
  3042. // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
  3043. seriesElement.attr({
  3044. 'ct:series-name': series.name,
  3045. 'ct:meta': Chartist.serialize(series.meta)
  3046. });
  3047. // Use series class from series data or if not set generate one
  3048. seriesElement.addClass([
  3049. options.classNames.series,
  3050. (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))
  3051. ].join(' '));
  3052. var pathCoordinates = [],
  3053. pathData = [];
  3054. data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {
  3055. var p = {
  3056. x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),
  3057. y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])
  3058. };
  3059. pathCoordinates.push(p.x, p.y);
  3060. pathData.push({
  3061. value: value,
  3062. valueIndex: valueIndex,
  3063. meta: Chartist.getMetaData(series, valueIndex)
  3064. });
  3065. }.bind(this));
  3066. var seriesOptions = {
  3067. lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),
  3068. showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),
  3069. showLine: Chartist.getSeriesOption(series, options, 'showLine'),
  3070. showArea: Chartist.getSeriesOption(series, options, 'showArea'),
  3071. areaBase: Chartist.getSeriesOption(series, options, 'areaBase')
  3072. };
  3073. var smoothing = typeof seriesOptions.lineSmooth === 'function' ?
  3074. seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());
  3075. // Interpolating path where pathData will be used to annotate each path element so we can trace back the original
  3076. // index, value and meta data
  3077. var path = smoothing(pathCoordinates, pathData);
  3078. // If we should show points we need to create them now to avoid secondary loop
  3079. // Points are drawn from the pathElements returned by the interpolation function
  3080. // Small offset for Firefox to render squares correctly
  3081. if (seriesOptions.showPoint) {
  3082. path.pathElements.forEach(function(pathElement) {
  3083. var point = seriesElement.elem('line', {
  3084. x1: pathElement.x,
  3085. y1: pathElement.y,
  3086. x2: pathElement.x + 0.01,
  3087. y2: pathElement.y
  3088. }, options.classNames.point).attr({
  3089. 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),
  3090. 'ct:meta': Chartist.serialize(pathElement.data.meta)
  3091. });
  3092. this.eventEmitter.emit('draw', {
  3093. type: 'point',
  3094. value: pathElement.data.value,
  3095. index: pathElement.data.valueIndex,
  3096. meta: pathElement.data.meta,
  3097. series: series,
  3098. seriesIndex: seriesIndex,
  3099. axisX: axisX,
  3100. axisY: axisY,
  3101. group: seriesElement,
  3102. element: point,
  3103. x: pathElement.x,
  3104. y: pathElement.y
  3105. });
  3106. }.bind(this));
  3107. }
  3108. if(seriesOptions.showLine) {
  3109. var line = seriesElement.elem('path', {
  3110. d: path.stringify()
  3111. }, options.classNames.line, true);
  3112. this.eventEmitter.emit('draw', {
  3113. type: 'line',
  3114. values: data.normalized.series[seriesIndex],
  3115. path: path.clone(),
  3116. chartRect: chartRect,
  3117. index: seriesIndex,
  3118. series: series,
  3119. seriesIndex: seriesIndex,
  3120. seriesMeta: series.meta,
  3121. axisX: axisX,
  3122. axisY: axisY,
  3123. group: seriesElement,
  3124. element: line
  3125. });
  3126. }
  3127. // Area currently only works with axes that support a range!
  3128. if(seriesOptions.showArea && axisY.range) {
  3129. // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that
  3130. // the area is not drawn outside the chart area.
  3131. var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);
  3132. // We project the areaBase value into screen coordinates
  3133. var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);
  3134. // In order to form the area we'll first split the path by move commands so we can chunk it up into segments
  3135. path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {
  3136. // We filter only "solid" segments that contain more than one point. Otherwise there's no need for an area
  3137. return pathSegment.pathElements.length > 1;
  3138. }).map(function convertToArea(solidPathSegments) {
  3139. // Receiving the filtered solid path segments we can now convert those segments into fill areas
  3140. var firstElement = solidPathSegments.pathElements[0];
  3141. var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];
  3142. // Cloning the solid path segment with closing option and removing the first move command from the clone
  3143. // We then insert a new move that should start at the area base and draw a straight line up or down
  3144. // at the end of the path we add an additional straight line to the projected area base value
  3145. // As the closing option is set our path will be automatically closed
  3146. return solidPathSegments.clone(true)
  3147. .position(0)
  3148. .remove(1)
  3149. .move(firstElement.x, areaBaseProjected)
  3150. .line(firstElement.x, firstElement.y)
  3151. .position(solidPathSegments.pathElements.length + 1)
  3152. .line(lastElement.x, areaBaseProjected);
  3153. }).forEach(function createArea(areaPath) {
  3154. // For each of our newly created area paths, we'll now create path elements by stringifying our path objects
  3155. // and adding the created DOM elements to the correct series group
  3156. var area = seriesElement.elem('path', {
  3157. d: areaPath.stringify()
  3158. }, options.classNames.area, true);
  3159. // Emit an event for each area that was drawn
  3160. this.eventEmitter.emit('draw', {
  3161. type: 'area',
  3162. values: data.normalized.series[seriesIndex],
  3163. path: areaPath.clone(),
  3164. series: series,
  3165. seriesIndex: seriesIndex,
  3166. axisX: axisX,
  3167. axisY: axisY,
  3168. chartRect: chartRect,
  3169. index: seriesIndex,
  3170. group: seriesElement,
  3171. element: area
  3172. });
  3173. }.bind(this));
  3174. }
  3175. }.bind(this));
  3176. this.eventEmitter.emit('created', {
  3177. bounds: axisY.bounds,
  3178. chartRect: chartRect,
  3179. axisX: axisX,
  3180. axisY: axisY,
  3181. svg: this.svg,
  3182. options: options
  3183. });
  3184. }
  3185. /**
  3186. * This method creates a new line chart.
  3187. *
  3188. * @memberof Chartist.Line
  3189. * @param {String|Node} query A selector query string or directly a DOM element
  3190. * @param {Object} data The data object that needs to consist of a labels and a series array
  3191. * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
  3192. * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
  3193. * @return {Object} An object which exposes the API for the created chart
  3194. *
  3195. * @example
  3196. * // Create a simple line chart
  3197. * var data = {
  3198. * // A labels array that can contain any sort of values
  3199. * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  3200. * // Our series array that contains series objects or in this case series data arrays
  3201. * series: [
  3202. * [5, 2, 4, 2, 0]
  3203. * ]
  3204. * };
  3205. *
  3206. * // As options we currently only set a static size of 300x200 px
  3207. * var options = {
  3208. * width: '300px',
  3209. * height: '200px'
  3210. * };
  3211. *
  3212. * // In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options
  3213. * new Chartist.Line('.ct-chart', data, options);
  3214. *
  3215. * @example
  3216. * // Use specific interpolation function with configuration from the Chartist.Interpolation module
  3217. *
  3218. * var chart = new Chartist.Line('.ct-chart', {
  3219. * labels: [1, 2, 3, 4, 5],
  3220. * series: [
  3221. * [1, 1, 8, 1, 7]
  3222. * ]
  3223. * }, {
  3224. * lineSmooth: Chartist.Interpolation.cardinal({
  3225. * tension: 0.2
  3226. * })
  3227. * });
  3228. *
  3229. * @example
  3230. * // Create a line chart with responsive options
  3231. *
  3232. * var data = {
  3233. * // A labels array that can contain any sort of values
  3234. * labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
  3235. * // Our series array that contains series objects or in this case series data arrays
  3236. * series: [
  3237. * [5, 2, 4, 2, 0]
  3238. * ]
  3239. * };
  3240. *
  3241. * // In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
  3242. * var responsiveOptions = [
  3243. * ['screen and (min-width: 641px) and (max-width: 1024px)', {
  3244. * showPoint: false,
  3245. * axisX: {
  3246. * labelInterpolationFnc: function(value) {
  3247. * // Will return Mon, Tue, Wed etc. on medium screens
  3248. * return value.slice(0, 3);
  3249. * }
  3250. * }
  3251. * }],
  3252. * ['screen and (max-width: 640px)', {
  3253. * showLine: false,
  3254. * axisX: {
  3255. * labelInterpolationFnc: function(value) {
  3256. * // Will return M, T, W etc. on small screens
  3257. * return value[0];
  3258. * }
  3259. * }
  3260. * }]
  3261. * ];
  3262. *
  3263. * new Chartist.Line('.ct-chart', data, null, responsiveOptions);
  3264. *
  3265. */
  3266. function Line(query, data, options, responsiveOptions) {
  3267. Chartist.Line.super.constructor.call(this,
  3268. query,
  3269. data,
  3270. defaultOptions,
  3271. Chartist.extend({}, defaultOptions, options),
  3272. responsiveOptions);
  3273. }
  3274. // Creating line chart type in Chartist namespace
  3275. Chartist.Line = Chartist.Base.extend({
  3276. constructor: Line,
  3277. createChart: createChart
  3278. });
  3279. }(window, document, Chartist));
  3280. ;/**
  3281. * The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts.
  3282. *
  3283. * @module Chartist.Bar
  3284. */
  3285. /* global Chartist */
  3286. (function(window, document, Chartist){
  3287. 'use strict';
  3288. /**
  3289. * Default options in bar charts. Expand the code view to see a detailed list of options with comments.
  3290. *
  3291. * @memberof Chartist.Bar
  3292. */
  3293. var defaultOptions = {
  3294. // Options for X-Axis
  3295. axisX: {
  3296. // The offset of the chart drawing area to the border of the container
  3297. offset: 30,
  3298. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  3299. position: 'end',
  3300. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  3301. labelOffset: {
  3302. x: 0,
  3303. y: 0
  3304. },
  3305. // If labels should be shown or not
  3306. showLabel: true,
  3307. // If the axis grid should be drawn or not
  3308. showGrid: true,
  3309. // Interpolation function that allows you to intercept the value from the axis label
  3310. labelInterpolationFnc: Chartist.noop,
  3311. // This value specifies the minimum width in pixel of the scale steps
  3312. scaleMinSpace: 30,
  3313. // Use only integer values (whole numbers) for the scale steps
  3314. onlyInteger: false
  3315. },
  3316. // Options for Y-Axis
  3317. axisY: {
  3318. // The offset of the chart drawing area to the border of the container
  3319. offset: 40,
  3320. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  3321. position: 'start',
  3322. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  3323. labelOffset: {
  3324. x: 0,
  3325. y: 0
  3326. },
  3327. // If labels should be shown or not
  3328. showLabel: true,
  3329. // If the axis grid should be drawn or not
  3330. showGrid: true,
  3331. // Interpolation function that allows you to intercept the value from the axis label
  3332. labelInterpolationFnc: Chartist.noop,
  3333. // This value specifies the minimum height in pixel of the scale steps
  3334. scaleMinSpace: 20,
  3335. // Use only integer values (whole numbers) for the scale steps
  3336. onlyInteger: false
  3337. },
  3338. // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
  3339. width: undefined,
  3340. // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
  3341. height: undefined,
  3342. // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
  3343. high: undefined,
  3344. // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
  3345. low: undefined,
  3346. // Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale.
  3347. referenceValue: 0,
  3348. // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
  3349. chartPadding: {
  3350. top: 15,
  3351. right: 15,
  3352. bottom: 5,
  3353. left: 10
  3354. },
  3355. // Specify the distance in pixel of bars in a group
  3356. seriesBarDistance: 15,
  3357. // If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options.
  3358. stackBars: false,
  3359. // If set to 'overlap' this property will force the stacked bars to draw from the zero line.
  3360. // If set to 'accumulate' this property will form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect.
  3361. stackMode: 'accumulate',
  3362. // Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values.
  3363. horizontalBars: false,
  3364. // If set to true then each bar will represent a series and the data array is expected to be a one dimensional array of data values rather than a series array of series. This is useful if the bar chart should represent a profile rather than some data over time.
  3365. distributeSeries: false,
  3366. // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
  3367. reverseData: false,
  3368. // If the bar chart should add a background fill to the .ct-grids group.
  3369. showGridBackground: false,
  3370. // Override the class names that get used to generate the SVG structure of the chart
  3371. classNames: {
  3372. chart: 'ct-chart-bar',
  3373. horizontalBars: 'ct-horizontal-bars',
  3374. label: 'ct-label',
  3375. labelGroup: 'ct-labels',
  3376. series: 'ct-series',
  3377. bar: 'ct-bar',
  3378. grid: 'ct-grid',
  3379. gridGroup: 'ct-grids',
  3380. gridBackground: 'ct-grid-background',
  3381. vertical: 'ct-vertical',
  3382. horizontal: 'ct-horizontal',
  3383. start: 'ct-start',
  3384. end: 'ct-end'
  3385. }
  3386. };
  3387. /**
  3388. * Creates a new chart
  3389. *
  3390. */
  3391. function createChart(options) {
  3392. var data;
  3393. var highLow;
  3394. if(options.distributeSeries) {
  3395. data = Chartist.normalizeData(this.data, options.reverseData, options.horizontalBars ? 'x' : 'y');
  3396. data.normalized.series = data.normalized.series.map(function(value) {
  3397. return [value];
  3398. });
  3399. } else {
  3400. data = Chartist.normalizeData(this.data, options.reverseData, options.horizontalBars ? 'x' : 'y');
  3401. }
  3402. // Create new svg element
  3403. this.svg = Chartist.createSvg(
  3404. this.container,
  3405. options.width,
  3406. options.height,
  3407. options.classNames.chart + (options.horizontalBars ? ' ' + options.classNames.horizontalBars : '')
  3408. );
  3409. // Drawing groups in correct order
  3410. var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);
  3411. var seriesGroup = this.svg.elem('g');
  3412. var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);
  3413. if(options.stackBars && data.normalized.series.length !== 0) {
  3414. // If stacked bars we need to calculate the high low from stacked values from each series
  3415. var serialSums = Chartist.serialMap(data.normalized.series, function serialSums() {
  3416. return Array.prototype.slice.call(arguments).map(function(value) {
  3417. return value;
  3418. }).reduce(function(prev, curr) {
  3419. return {
  3420. x: prev.x + (curr && curr.x) || 0,
  3421. y: prev.y + (curr && curr.y) || 0
  3422. };
  3423. }, {x: 0, y: 0});
  3424. });
  3425. highLow = Chartist.getHighLow([serialSums], options, options.horizontalBars ? 'x' : 'y');
  3426. } else {
  3427. highLow = Chartist.getHighLow(data.normalized.series, options, options.horizontalBars ? 'x' : 'y');
  3428. }
  3429. // Overrides of high / low from settings
  3430. highLow.high = +options.high || (options.high === 0 ? 0 : highLow.high);
  3431. highLow.low = +options.low || (options.low === 0 ? 0 : highLow.low);
  3432. var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
  3433. var valueAxis,
  3434. labelAxisTicks,
  3435. labelAxis,
  3436. axisX,
  3437. axisY;
  3438. // We need to set step count based on some options combinations
  3439. if(options.distributeSeries && options.stackBars) {
  3440. // If distributed series are enabled and bars need to be stacked, we'll only have one bar and therefore should
  3441. // use only the first label for the step axis
  3442. labelAxisTicks = data.normalized.labels.slice(0, 1);
  3443. } else {
  3444. // If distributed series are enabled but stacked bars aren't, we should use the series labels
  3445. // If we are drawing a regular bar chart with two dimensional series data, we just use the labels array
  3446. // as the bars are normalized
  3447. labelAxisTicks = data.normalized.labels;
  3448. }
  3449. // Set labelAxis and valueAxis based on the horizontalBars setting. This setting will flip the axes if necessary.
  3450. if(options.horizontalBars) {
  3451. if(options.axisX.type === undefined) {
  3452. valueAxis = axisX = new Chartist.AutoScaleAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
  3453. highLow: highLow,
  3454. referenceValue: 0
  3455. }));
  3456. } else {
  3457. valueAxis = axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
  3458. highLow: highLow,
  3459. referenceValue: 0
  3460. }));
  3461. }
  3462. if(options.axisY.type === undefined) {
  3463. labelAxis = axisY = new Chartist.StepAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, {
  3464. ticks: labelAxisTicks
  3465. });
  3466. } else {
  3467. labelAxis = axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);
  3468. }
  3469. } else {
  3470. if(options.axisX.type === undefined) {
  3471. labelAxis = axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, {
  3472. ticks: labelAxisTicks
  3473. });
  3474. } else {
  3475. labelAxis = axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);
  3476. }
  3477. if(options.axisY.type === undefined) {
  3478. valueAxis = axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
  3479. highLow: highLow,
  3480. referenceValue: 0
  3481. }));
  3482. } else {
  3483. valueAxis = axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
  3484. highLow: highLow,
  3485. referenceValue: 0
  3486. }));
  3487. }
  3488. }
  3489. // Projected 0 point
  3490. var zeroPoint = options.horizontalBars ? (chartRect.x1 + valueAxis.projectValue(0)) : (chartRect.y1 - valueAxis.projectValue(0));
  3491. // Used to track the screen coordinates of stacked bars
  3492. var stackedBarValues = [];
  3493. labelAxis.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3494. valueAxis.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3495. if (options.showGridBackground) {
  3496. Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
  3497. }
  3498. // Draw the series
  3499. data.raw.series.forEach(function(series, seriesIndex) {
  3500. // Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc.
  3501. var biPol = seriesIndex - (data.raw.series.length - 1) / 2;
  3502. // Half of the period width between vertical grid lines used to position bars
  3503. var periodHalfLength;
  3504. // Current series SVG element
  3505. var seriesElement;
  3506. // We need to set periodHalfLength based on some options combinations
  3507. if(options.distributeSeries && !options.stackBars) {
  3508. // If distributed series are enabled but stacked bars aren't, we need to use the length of the normaizedData array
  3509. // which is the series count and divide by 2
  3510. periodHalfLength = labelAxis.axisLength / data.normalized.series.length / 2;
  3511. } else if(options.distributeSeries && options.stackBars) {
  3512. // If distributed series and stacked bars are enabled we'll only get one bar so we should just divide the axis
  3513. // length by 2
  3514. periodHalfLength = labelAxis.axisLength / 2;
  3515. } else {
  3516. // On regular bar charts we should just use the series length
  3517. periodHalfLength = labelAxis.axisLength / data.normalized.series[seriesIndex].length / 2;
  3518. }
  3519. // Adding the series group to the series element
  3520. seriesElement = seriesGroup.elem('g');
  3521. // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
  3522. seriesElement.attr({
  3523. 'ct:series-name': series.name,
  3524. 'ct:meta': Chartist.serialize(series.meta)
  3525. });
  3526. // Use series class from series data or if not set generate one
  3527. seriesElement.addClass([
  3528. options.classNames.series,
  3529. (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))
  3530. ].join(' '));
  3531. data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {
  3532. var projected,
  3533. bar,
  3534. previousStack,
  3535. labelAxisValueIndex;
  3536. // We need to set labelAxisValueIndex based on some options combinations
  3537. if(options.distributeSeries && !options.stackBars) {
  3538. // If distributed series are enabled but stacked bars aren't, we can use the seriesIndex for later projection
  3539. // on the step axis for label positioning
  3540. labelAxisValueIndex = seriesIndex;
  3541. } else if(options.distributeSeries && options.stackBars) {
  3542. // If distributed series and stacked bars are enabled, we will only get one bar and therefore always use
  3543. // 0 for projection on the label step axis
  3544. labelAxisValueIndex = 0;
  3545. } else {
  3546. // On regular bar charts we just use the value index to project on the label step axis
  3547. labelAxisValueIndex = valueIndex;
  3548. }
  3549. // We need to transform coordinates differently based on the chart layout
  3550. if(options.horizontalBars) {
  3551. projected = {
  3552. x: chartRect.x1 + valueAxis.projectValue(value && value.x ? value.x : 0, valueIndex, data.normalized.series[seriesIndex]),
  3553. y: chartRect.y1 - labelAxis.projectValue(value && value.y ? value.y : 0, labelAxisValueIndex, data.normalized.series[seriesIndex])
  3554. };
  3555. } else {
  3556. projected = {
  3557. x: chartRect.x1 + labelAxis.projectValue(value && value.x ? value.x : 0, labelAxisValueIndex, data.normalized.series[seriesIndex]),
  3558. y: chartRect.y1 - valueAxis.projectValue(value && value.y ? value.y : 0, valueIndex, data.normalized.series[seriesIndex])
  3559. }
  3560. }
  3561. // If the label axis is a step based axis we will offset the bar into the middle of between two steps using
  3562. // the periodHalfLength value. Also we do arrange the different series so that they align up to each other using
  3563. // the seriesBarDistance. If we don't have a step axis, the bar positions can be chosen freely so we should not
  3564. // add any automated positioning.
  3565. if(labelAxis instanceof Chartist.StepAxis) {
  3566. // Offset to center bar between grid lines, but only if the step axis is not stretched
  3567. if(!labelAxis.options.stretch) {
  3568. projected[labelAxis.units.pos] += periodHalfLength * (options.horizontalBars ? -1 : 1);
  3569. }
  3570. // Using bi-polar offset for multiple series if no stacked bars or series distribution is used
  3571. projected[labelAxis.units.pos] += (options.stackBars || options.distributeSeries) ? 0 : biPol * options.seriesBarDistance * (options.horizontalBars ? -1 : 1);
  3572. }
  3573. // Enter value in stacked bar values used to remember previous screen value for stacking up bars
  3574. previousStack = stackedBarValues[valueIndex] || zeroPoint;
  3575. stackedBarValues[valueIndex] = previousStack - (zeroPoint - projected[labelAxis.counterUnits.pos]);
  3576. // Skip if value is undefined
  3577. if(value === undefined) {
  3578. return;
  3579. }
  3580. var positions = {};
  3581. positions[labelAxis.units.pos + '1'] = projected[labelAxis.units.pos];
  3582. positions[labelAxis.units.pos + '2'] = projected[labelAxis.units.pos];
  3583. if(options.stackBars && (options.stackMode === 'accumulate' || !options.stackMode)) {
  3584. // Stack mode: accumulate (default)
  3585. // If bars are stacked we use the stackedBarValues reference and otherwise base all bars off the zero line
  3586. // We want backwards compatibility, so the expected fallback without the 'stackMode' option
  3587. // to be the original behaviour (accumulate)
  3588. positions[labelAxis.counterUnits.pos + '1'] = previousStack;
  3589. positions[labelAxis.counterUnits.pos + '2'] = stackedBarValues[valueIndex];
  3590. } else {
  3591. // Draw from the zero line normally
  3592. // This is also the same code for Stack mode: overlap
  3593. positions[labelAxis.counterUnits.pos + '1'] = zeroPoint;
  3594. positions[labelAxis.counterUnits.pos + '2'] = projected[labelAxis.counterUnits.pos];
  3595. }
  3596. // Limit x and y so that they are within the chart rect
  3597. positions.x1 = Math.min(Math.max(positions.x1, chartRect.x1), chartRect.x2);
  3598. positions.x2 = Math.min(Math.max(positions.x2, chartRect.x1), chartRect.x2);
  3599. positions.y1 = Math.min(Math.max(positions.y1, chartRect.y2), chartRect.y1);
  3600. positions.y2 = Math.min(Math.max(positions.y2, chartRect.y2), chartRect.y1);
  3601. var metaData = Chartist.getMetaData(series, valueIndex);
  3602. // Create bar element
  3603. bar = seriesElement.elem('line', positions, options.classNames.bar).attr({
  3604. 'ct:value': [value.x, value.y].filter(Chartist.isNumeric).join(','),
  3605. 'ct:meta': Chartist.serialize(metaData)
  3606. });
  3607. this.eventEmitter.emit('draw', Chartist.extend({
  3608. type: 'bar',
  3609. value: value,
  3610. index: valueIndex,
  3611. meta: metaData,
  3612. series: series,
  3613. seriesIndex: seriesIndex,
  3614. axisX: axisX,
  3615. axisY: axisY,
  3616. chartRect: chartRect,
  3617. group: seriesElement,
  3618. element: bar
  3619. }, positions));
  3620. }.bind(this));
  3621. }.bind(this));
  3622. this.eventEmitter.emit('created', {
  3623. bounds: valueAxis.bounds,
  3624. chartRect: chartRect,
  3625. axisX: axisX,
  3626. axisY: axisY,
  3627. svg: this.svg,
  3628. options: options
  3629. });
  3630. }
  3631. /**
  3632. * This method creates a new bar chart and returns API object that you can use for later changes.
  3633. *
  3634. * @memberof Chartist.Bar
  3635. * @param {String|Node} query A selector query string or directly a DOM element
  3636. * @param {Object} data The data object that needs to consist of a labels and a series array
  3637. * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
  3638. * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
  3639. * @return {Object} An object which exposes the API for the created chart
  3640. *
  3641. * @example
  3642. * // Create a simple bar chart
  3643. * var data = {
  3644. * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  3645. * series: [
  3646. * [5, 2, 4, 2, 0]
  3647. * ]
  3648. * };
  3649. *
  3650. * // In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object.
  3651. * new Chartist.Bar('.ct-chart', data);
  3652. *
  3653. * @example
  3654. * // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
  3655. * new Chartist.Bar('.ct-chart', {
  3656. * labels: [1, 2, 3, 4, 5, 6, 7],
  3657. * series: [
  3658. * [1, 3, 2, -5, -3, 1, -6],
  3659. * [-5, -2, -4, -1, 2, -3, 1]
  3660. * ]
  3661. * }, {
  3662. * seriesBarDistance: 12,
  3663. * low: -10,
  3664. * high: 10
  3665. * });
  3666. *
  3667. */
  3668. function Bar(query, data, options, responsiveOptions) {
  3669. Chartist.Bar.super.constructor.call(this,
  3670. query,
  3671. data,
  3672. defaultOptions,
  3673. Chartist.extend({}, defaultOptions, options),
  3674. responsiveOptions);
  3675. }
  3676. // Creating bar chart type in Chartist namespace
  3677. Chartist.Bar = Chartist.Base.extend({
  3678. constructor: Bar,
  3679. createChart: createChart
  3680. });
  3681. }(window, document, Chartist));
  3682. ;/**
  3683. * The pie chart module of Chartist that can be used to draw pie, donut or gauge charts
  3684. *
  3685. * @module Chartist.Pie
  3686. */
  3687. /* global Chartist */
  3688. (function(window, document, Chartist) {
  3689. 'use strict';
  3690. /**
  3691. * Default options in line charts. Expand the code view to see a detailed list of options with comments.
  3692. *
  3693. * @memberof Chartist.Pie
  3694. */
  3695. var defaultOptions = {
  3696. // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
  3697. width: undefined,
  3698. // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
  3699. height: undefined,
  3700. // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
  3701. chartPadding: 5,
  3702. // Override the class names that are used to generate the SVG structure of the chart
  3703. classNames: {
  3704. chartPie: 'ct-chart-pie',
  3705. chartDonut: 'ct-chart-donut',
  3706. series: 'ct-series',
  3707. slicePie: 'ct-slice-pie',
  3708. sliceDonut: 'ct-slice-donut',
  3709. sliceDonutSolid: 'ct-slice-donut-solid',
  3710. label: 'ct-label'
  3711. },
  3712. // The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise.
  3713. startAngle: 0,
  3714. // An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts.
  3715. total: undefined,
  3716. // If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices.
  3717. donut: false,
  3718. // If specified the donut segments will be drawn as shapes instead of strokes.
  3719. donutSolid: false,
  3720. // Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future.
  3721. // This option can be set as number or string to specify a relative width (i.e. 100 or '30%').
  3722. donutWidth: 60,
  3723. // If a label should be shown or not
  3724. showLabel: true,
  3725. // Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center.
  3726. labelOffset: 0,
  3727. // This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option.
  3728. labelPosition: 'inside',
  3729. // An interpolation function for the label value
  3730. labelInterpolationFnc: Chartist.noop,
  3731. // Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center.
  3732. labelDirection: 'neutral',
  3733. // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
  3734. reverseData: false,
  3735. // If true empty values will be ignored to avoid drawing unncessary slices and labels
  3736. ignoreEmptyValues: false
  3737. };
  3738. /**
  3739. * Determines SVG anchor position based on direction and center parameter
  3740. *
  3741. * @param center
  3742. * @param label
  3743. * @param direction
  3744. * @return {string}
  3745. */
  3746. function determineAnchorPosition(center, label, direction) {
  3747. var toTheRight = label.x > center.x;
  3748. if(toTheRight && direction === 'explode' ||
  3749. !toTheRight && direction === 'implode') {
  3750. return 'start';
  3751. } else if(toTheRight && direction === 'implode' ||
  3752. !toTheRight && direction === 'explode') {
  3753. return 'end';
  3754. } else {
  3755. return 'middle';
  3756. }
  3757. }
  3758. /**
  3759. * Creates the pie chart
  3760. *
  3761. * @param options
  3762. */
  3763. function createChart(options) {
  3764. var data = Chartist.normalizeData(this.data);
  3765. var seriesGroups = [],
  3766. labelsGroup,
  3767. chartRect,
  3768. radius,
  3769. labelRadius,
  3770. totalDataSum,
  3771. startAngle = options.startAngle;
  3772. // Create SVG.js draw
  3773. this.svg = Chartist.createSvg(this.container, options.width, options.height,options.donut ? options.classNames.chartDonut : options.classNames.chartPie);
  3774. // Calculate charting rect
  3775. chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
  3776. // Get biggest circle radius possible within chartRect
  3777. radius = Math.min(chartRect.width() / 2, chartRect.height() / 2);
  3778. // Calculate total of all series to get reference value or use total reference from optional options
  3779. totalDataSum = options.total || data.normalized.series.reduce(function(previousValue, currentValue) {
  3780. return previousValue + currentValue;
  3781. }, 0);
  3782. var donutWidth = Chartist.quantity(options.donutWidth);
  3783. if (donutWidth.unit === '%') {
  3784. donutWidth.value *= radius / 100;
  3785. }
  3786. // If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside
  3787. // Unfortunately this is not possible with the current SVG Spec
  3788. // See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html
  3789. radius -= options.donut && !options.donutSolid ? donutWidth.value / 2 : 0;
  3790. // If labelPosition is set to `outside` or a donut chart is drawn then the label position is at the radius,
  3791. // if regular pie chart it's half of the radius
  3792. if(options.labelPosition === 'outside' || options.donut && !options.donutSolid) {
  3793. labelRadius = radius;
  3794. } else if(options.labelPosition === 'center') {
  3795. // If labelPosition is center we start with 0 and will later wait for the labelOffset
  3796. labelRadius = 0;
  3797. } else if(options.donutSolid) {
  3798. labelRadius = radius - donutWidth.value / 2;
  3799. } else {
  3800. // Default option is 'inside' where we use half the radius so the label will be placed in the center of the pie
  3801. // slice
  3802. labelRadius = radius / 2;
  3803. }
  3804. // Add the offset to the labelRadius where a negative offset means closed to the center of the chart
  3805. labelRadius += options.labelOffset;
  3806. // Calculate end angle based on total sum and current data value and offset with padding
  3807. var center = {
  3808. x: chartRect.x1 + chartRect.width() / 2,
  3809. y: chartRect.y2 + chartRect.height() / 2
  3810. };
  3811. // Check if there is only one non-zero value in the series array.
  3812. var hasSingleValInSeries = data.raw.series.filter(function(val) {
  3813. return val.hasOwnProperty('value') ? val.value !== 0 : val !== 0;
  3814. }).length === 1;
  3815. // Creating the series groups
  3816. data.raw.series.forEach(function(series, index) {
  3817. seriesGroups[index] = this.svg.elem('g', null, null);
  3818. }.bind(this));
  3819. //if we need to show labels we create the label group now
  3820. if(options.showLabel) {
  3821. labelsGroup = this.svg.elem('g', null, null);
  3822. }
  3823. // Draw the series
  3824. // initialize series groups
  3825. data.raw.series.forEach(function(series, index) {
  3826. // If current value is zero and we are ignoring empty values then skip to next value
  3827. if (data.normalized.series[index] === 0 && options.ignoreEmptyValues) return;
  3828. // If the series is an object and contains a name or meta data we add a custom attribute
  3829. seriesGroups[index].attr({
  3830. 'ct:series-name': series.name
  3831. });
  3832. // Use series class from series data or if not set generate one
  3833. seriesGroups[index].addClass([
  3834. options.classNames.series,
  3835. (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(index))
  3836. ].join(' '));
  3837. // If the whole dataset is 0 endAngle should be zero. Can't divide by 0.
  3838. var endAngle = (totalDataSum > 0 ? startAngle + data.normalized.series[index] / totalDataSum * 360 : 0);
  3839. // Use slight offset so there are no transparent hairline issues
  3840. var overlappigStartAngle = Math.max(0, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
  3841. // If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle
  3842. // with Z and use 359.99 degrees
  3843. if(endAngle - overlappigStartAngle >= 359.99) {
  3844. endAngle = overlappigStartAngle + 359.99;
  3845. }
  3846. var start = Chartist.polarToCartesian(center.x, center.y, radius, overlappigStartAngle),
  3847. end = Chartist.polarToCartesian(center.x, center.y, radius, endAngle);
  3848. var innerStart,
  3849. innerEnd,
  3850. donutSolidRadius;
  3851. // Create a new path element for the pie chart. If this isn't a donut chart we should close the path for a correct stroke
  3852. var path = new Chartist.Svg.Path(!options.donut || options.donutSolid)
  3853. .move(end.x, end.y)
  3854. .arc(radius, radius, 0, endAngle - startAngle > 180, 0, start.x, start.y);
  3855. // If regular pie chart (no donut) we add a line to the center of the circle for completing the pie
  3856. if(!options.donut) {
  3857. path.line(center.x, center.y);
  3858. } else if (options.donutSolid) {
  3859. donutSolidRadius = radius - donutWidth.value;
  3860. innerStart = Chartist.polarToCartesian(center.x, center.y, donutSolidRadius, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
  3861. innerEnd = Chartist.polarToCartesian(center.x, center.y, donutSolidRadius, endAngle);
  3862. path.line(innerStart.x, innerStart.y);
  3863. path.arc(donutSolidRadius, donutSolidRadius, 0, endAngle - startAngle > 180, 1, innerEnd.x, innerEnd.y);
  3864. }
  3865. // Create the SVG path
  3866. // If this is a donut chart we add the donut class, otherwise just a regular slice
  3867. var pathClassName = options.classNames.slicePie;
  3868. if (options.donut) {
  3869. pathClassName = options.classNames.sliceDonut;
  3870. if (options.donutSolid) {
  3871. pathClassName = options.classNames.sliceDonutSolid;
  3872. }
  3873. }
  3874. var pathElement = seriesGroups[index].elem('path', {
  3875. d: path.stringify()
  3876. }, pathClassName);
  3877. // Adding the pie series value to the path
  3878. pathElement.attr({
  3879. 'ct:value': data.normalized.series[index],
  3880. 'ct:meta': Chartist.serialize(series.meta)
  3881. });
  3882. // If this is a donut, we add the stroke-width as style attribute
  3883. if(options.donut && !options.donutSolid) {
  3884. pathElement._node.style.strokeWidth = donutWidth.value + 'px';
  3885. }
  3886. // Fire off draw event
  3887. this.eventEmitter.emit('draw', {
  3888. type: 'slice',
  3889. value: data.normalized.series[index],
  3890. totalDataSum: totalDataSum,
  3891. index: index,
  3892. meta: series.meta,
  3893. series: series,
  3894. group: seriesGroups[index],
  3895. element: pathElement,
  3896. path: path.clone(),
  3897. center: center,
  3898. radius: radius,
  3899. startAngle: startAngle,
  3900. endAngle: endAngle
  3901. });
  3902. // If we need to show labels we need to add the label for this slice now
  3903. if(options.showLabel) {
  3904. var labelPosition;
  3905. if(data.raw.series.length === 1) {
  3906. // If we have only 1 series, we can position the label in the center of the pie
  3907. labelPosition = {
  3908. x: center.x,
  3909. y: center.y
  3910. };
  3911. } else {
  3912. // Position at the labelRadius distance from center and between start and end angle
  3913. labelPosition = Chartist.polarToCartesian(
  3914. center.x,
  3915. center.y,
  3916. labelRadius,
  3917. startAngle + (endAngle - startAngle) / 2
  3918. );
  3919. }
  3920. var rawValue;
  3921. if(data.normalized.labels && !Chartist.isFalseyButZero(data.normalized.labels[index])) {
  3922. rawValue = data.normalized.labels[index];
  3923. } else {
  3924. rawValue = data.normalized.series[index];
  3925. }
  3926. var interpolatedValue = options.labelInterpolationFnc(rawValue, index);
  3927. if(interpolatedValue || interpolatedValue === 0) {
  3928. var labelElement = labelsGroup.elem('text', {
  3929. dx: labelPosition.x,
  3930. dy: labelPosition.y,
  3931. 'text-anchor': determineAnchorPosition(center, labelPosition, options.labelDirection)
  3932. }, options.classNames.label).text('' + interpolatedValue);
  3933. // Fire off draw event
  3934. this.eventEmitter.emit('draw', {
  3935. type: 'label',
  3936. index: index,
  3937. group: labelsGroup,
  3938. element: labelElement,
  3939. text: '' + interpolatedValue,
  3940. x: labelPosition.x,
  3941. y: labelPosition.y
  3942. });
  3943. }
  3944. }
  3945. // Set next startAngle to current endAngle.
  3946. // (except for last slice)
  3947. startAngle = endAngle;
  3948. }.bind(this));
  3949. this.eventEmitter.emit('created', {
  3950. chartRect: chartRect,
  3951. svg: this.svg,
  3952. options: options
  3953. });
  3954. }
  3955. /**
  3956. * This method creates a new pie chart and returns an object that can be used to redraw the chart.
  3957. *
  3958. * @memberof Chartist.Pie
  3959. * @param {String|Node} query A selector query string or directly a DOM element
  3960. * @param {Object} data The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group.
  3961. * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
  3962. * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
  3963. * @return {Object} An object with a version and an update method to manually redraw the chart
  3964. *
  3965. * @example
  3966. * // Simple pie chart example with four series
  3967. * new Chartist.Pie('.ct-chart', {
  3968. * series: [10, 2, 4, 3]
  3969. * });
  3970. *
  3971. * @example
  3972. * // Drawing a donut chart
  3973. * new Chartist.Pie('.ct-chart', {
  3974. * series: [10, 2, 4, 3]
  3975. * }, {
  3976. * donut: true
  3977. * });
  3978. *
  3979. * @example
  3980. * // Using donut, startAngle and total to draw a gauge chart
  3981. * new Chartist.Pie('.ct-chart', {
  3982. * series: [20, 10, 30, 40]
  3983. * }, {
  3984. * donut: true,
  3985. * donutWidth: 20,
  3986. * startAngle: 270,
  3987. * total: 200
  3988. * });
  3989. *
  3990. * @example
  3991. * // Drawing a pie chart with padding and labels that are outside the pie
  3992. * new Chartist.Pie('.ct-chart', {
  3993. * series: [20, 10, 30, 40]
  3994. * }, {
  3995. * chartPadding: 30,
  3996. * labelOffset: 50,
  3997. * labelDirection: 'explode'
  3998. * });
  3999. *
  4000. * @example
  4001. * // Overriding the class names for individual series as well as a name and meta data.
  4002. * // The name will be written as ct:series-name attribute and the meta data will be serialized and written
  4003. * // to a ct:meta attribute.
  4004. * new Chartist.Pie('.ct-chart', {
  4005. * series: [{
  4006. * value: 20,
  4007. * name: 'Series 1',
  4008. * className: 'my-custom-class-one',
  4009. * meta: 'Meta One'
  4010. * }, {
  4011. * value: 10,
  4012. * name: 'Series 2',
  4013. * className: 'my-custom-class-two',
  4014. * meta: 'Meta Two'
  4015. * }, {
  4016. * value: 70,
  4017. * name: 'Series 3',
  4018. * className: 'my-custom-class-three',
  4019. * meta: 'Meta Three'
  4020. * }]
  4021. * });
  4022. */
  4023. function Pie(query, data, options, responsiveOptions) {
  4024. Chartist.Pie.super.constructor.call(this,
  4025. query,
  4026. data,
  4027. defaultOptions,
  4028. Chartist.extend({}, defaultOptions, options),
  4029. responsiveOptions);
  4030. }
  4031. // Creating pie chart type in Chartist namespace
  4032. Chartist.Pie = Chartist.Base.extend({
  4033. constructor: Pie,
  4034. createChart: createChart,
  4035. determineAnchorPosition: determineAnchorPosition
  4036. });
  4037. }(window, document, Chartist));
  4038. return Chartist;
  4039. }));