Chart.Bar.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. (function(){
  2. "use strict";
  3. var root = this,
  4. Chart = root.Chart,
  5. helpers = Chart.helpers;
  6. var defaultConfig = {
  7. //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
  8. scaleBeginAtZero : true,
  9. //Boolean - Whether grid lines are shown across the chart
  10. scaleShowGridLines : true,
  11. //String - Colour of the grid lines
  12. scaleGridLineColor : "rgba(0,0,0,.05)",
  13. //Number - Width of the grid lines
  14. scaleGridLineWidth : 1,
  15. //Boolean - Whether to show horizontal lines (except X axis)
  16. scaleShowHorizontalLines: true,
  17. //Boolean - Whether to show vertical lines (except Y axis)
  18. scaleShowVerticalLines: true,
  19. //Boolean - If there is a stroke on each bar
  20. barShowStroke : true,
  21. //Number - Pixel width of the bar stroke
  22. barStrokeWidth : 2,
  23. //Number - Spacing between each of the X value sets
  24. barValueSpacing : 5,
  25. //Number - Spacing between data sets within X values
  26. barDatasetSpacing : 1,
  27. //String - A legend template
  28. legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
  29. };
  30. Chart.Type.extend({
  31. name: "Bar",
  32. defaults : defaultConfig,
  33. initialize: function(data){
  34. //Expose options as a scope variable here so we can access it in the ScaleClass
  35. var options = this.options;
  36. this.ScaleClass = Chart.Scale.extend({
  37. offsetGridLines : true,
  38. calculateBarX : function(datasetCount, datasetIndex, barIndex){
  39. //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
  40. var xWidth = this.calculateBaseWidth(),
  41. xAbsolute = this.calculateX(barIndex) - (xWidth/2),
  42. barWidth = this.calculateBarWidth(datasetCount);
  43. return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
  44. },
  45. calculateBaseWidth : function(){
  46. return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
  47. },
  48. calculateBarWidth : function(datasetCount){
  49. //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
  50. var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
  51. return (baseWidth / datasetCount);
  52. }
  53. });
  54. this.datasets = [];
  55. //Set up tooltip events on the chart
  56. if (this.options.showTooltips){
  57. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  58. var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
  59. this.eachBars(function(bar){
  60. bar.restore(['fillColor', 'strokeColor']);
  61. });
  62. helpers.each(activeBars, function(activeBar){
  63. activeBar.fillColor = activeBar.highlightFill;
  64. activeBar.strokeColor = activeBar.highlightStroke;
  65. });
  66. this.showTooltip(activeBars);
  67. });
  68. }
  69. //Declare the extension of the default point, to cater for the options passed in to the constructor
  70. this.BarClass = Chart.Rectangle.extend({
  71. strokeWidth : this.options.barStrokeWidth,
  72. showStroke : this.options.barShowStroke,
  73. ctx : this.chart.ctx
  74. });
  75. //Iterate through each of the datasets, and build this into a property of the chart
  76. helpers.each(data.datasets,function(dataset,datasetIndex){
  77. var datasetObject = {
  78. label : dataset.label || null,
  79. fillColor : dataset.fillColor,
  80. strokeColor : dataset.strokeColor,
  81. bars : []
  82. };
  83. this.datasets.push(datasetObject);
  84. helpers.each(dataset.data,function(dataPoint,index){
  85. //Add a new point for each piece of data, passing any required data to draw.
  86. datasetObject.bars.push(new this.BarClass({
  87. value : dataPoint,
  88. label : data.labels[index],
  89. datasetLabel: dataset.label,
  90. strokeColor : dataset.strokeColor,
  91. fillColor : dataset.fillColor,
  92. highlightFill : dataset.highlightFill || dataset.fillColor,
  93. highlightStroke : dataset.highlightStroke || dataset.strokeColor
  94. }));
  95. },this);
  96. },this);
  97. this.buildScale(data.labels);
  98. this.BarClass.prototype.base = this.scale.endPoint;
  99. this.eachBars(function(bar, index, datasetIndex){
  100. helpers.extend(bar, {
  101. width : this.scale.calculateBarWidth(this.datasets.length),
  102. x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
  103. y: this.scale.endPoint
  104. });
  105. bar.save();
  106. }, this);
  107. this.render();
  108. },
  109. update : function(){
  110. this.scale.update();
  111. // Reset any highlight colours before updating.
  112. helpers.each(this.activeElements, function(activeElement){
  113. activeElement.restore(['fillColor', 'strokeColor']);
  114. });
  115. this.eachBars(function(bar){
  116. bar.save();
  117. });
  118. this.render();
  119. },
  120. eachBars : function(callback){
  121. helpers.each(this.datasets,function(dataset, datasetIndex){
  122. helpers.each(dataset.bars, callback, this, datasetIndex);
  123. },this);
  124. },
  125. getBarsAtEvent : function(e){
  126. var barsArray = [],
  127. eventPosition = helpers.getRelativePosition(e),
  128. datasetIterator = function(dataset){
  129. barsArray.push(dataset.bars[barIndex]);
  130. },
  131. barIndex;
  132. for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
  133. for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
  134. if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
  135. helpers.each(this.datasets, datasetIterator);
  136. return barsArray;
  137. }
  138. }
  139. }
  140. return barsArray;
  141. },
  142. buildScale : function(labels){
  143. var self = this;
  144. var dataTotal = function(){
  145. var values = [];
  146. self.eachBars(function(bar){
  147. values.push(bar.value);
  148. });
  149. return values;
  150. };
  151. var scaleOptions = {
  152. templateString : this.options.scaleLabel,
  153. height : this.chart.height,
  154. width : this.chart.width,
  155. ctx : this.chart.ctx,
  156. textColor : this.options.scaleFontColor,
  157. fontSize : this.options.scaleFontSize,
  158. fontStyle : this.options.scaleFontStyle,
  159. fontFamily : this.options.scaleFontFamily,
  160. valuesCount : labels.length,
  161. beginAtZero : this.options.scaleBeginAtZero,
  162. integersOnly : this.options.scaleIntegersOnly,
  163. calculateYRange: function(currentHeight){
  164. var updatedRanges = helpers.calculateScaleRange(
  165. dataTotal(),
  166. currentHeight,
  167. this.fontSize,
  168. this.beginAtZero,
  169. this.integersOnly
  170. );
  171. helpers.extend(this, updatedRanges);
  172. },
  173. xLabels : labels,
  174. font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
  175. lineWidth : this.options.scaleLineWidth,
  176. lineColor : this.options.scaleLineColor,
  177. showHorizontalLines : this.options.scaleShowHorizontalLines,
  178. showVerticalLines : this.options.scaleShowVerticalLines,
  179. gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
  180. gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
  181. padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
  182. showLabels : this.options.scaleShowLabels,
  183. display : this.options.showScale
  184. };
  185. if (this.options.scaleOverride){
  186. helpers.extend(scaleOptions, {
  187. calculateYRange: helpers.noop,
  188. steps: this.options.scaleSteps,
  189. stepValue: this.options.scaleStepWidth,
  190. min: this.options.scaleStartValue,
  191. max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
  192. });
  193. }
  194. this.scale = new this.ScaleClass(scaleOptions);
  195. },
  196. addData : function(valuesArray,label){
  197. //Map the values array for each of the datasets
  198. helpers.each(valuesArray,function(value,datasetIndex){
  199. //Add a new point for each piece of data, passing any required data to draw.
  200. this.datasets[datasetIndex].bars.push(new this.BarClass({
  201. value : value,
  202. label : label,
  203. x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
  204. y: this.scale.endPoint,
  205. width : this.scale.calculateBarWidth(this.datasets.length),
  206. base : this.scale.endPoint,
  207. strokeColor : this.datasets[datasetIndex].strokeColor,
  208. fillColor : this.datasets[datasetIndex].fillColor
  209. }));
  210. },this);
  211. this.scale.addXLabel(label);
  212. //Then re-render the chart.
  213. this.update();
  214. },
  215. removeData : function(){
  216. this.scale.removeXLabel();
  217. //Then re-render the chart.
  218. helpers.each(this.datasets,function(dataset){
  219. dataset.bars.shift();
  220. },this);
  221. this.update();
  222. },
  223. reflow : function(){
  224. helpers.extend(this.BarClass.prototype,{
  225. y: this.scale.endPoint,
  226. base : this.scale.endPoint
  227. });
  228. var newScaleProps = helpers.extend({
  229. height : this.chart.height,
  230. width : this.chart.width
  231. });
  232. this.scale.update(newScaleProps);
  233. },
  234. draw : function(ease){
  235. var easingDecimal = ease || 1;
  236. this.clear();
  237. var ctx = this.chart.ctx;
  238. this.scale.draw(easingDecimal);
  239. //Draw all the bars for each dataset
  240. helpers.each(this.datasets,function(dataset,datasetIndex){
  241. helpers.each(dataset.bars,function(bar,index){
  242. if (bar.hasValue()){
  243. bar.base = this.scale.endPoint;
  244. //Transition then draw
  245. bar.transition({
  246. x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
  247. y : this.scale.calculateY(bar.value),
  248. width : this.scale.calculateBarWidth(this.datasets.length)
  249. }, easingDecimal).draw();
  250. }
  251. },this);
  252. },this);
  253. }
  254. });
  255. }).call(this);