4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-chart-series-Bar'>/**
19 </span> * Creates a Bar Chart. A Bar Chart is a useful visualization technique to display quantitative information for
20 * different categories that can show some progression (or regression) in the dataset. As with all other series, the Bar
21 * Series must be appended in the *series* Chart array configuration. See the Chart documentation for more information.
22 * A typical configuration object for the bar series could be:
24 * {@img Ext.chart.series.Bar/Ext.chart.series.Bar.png Ext.chart.series.Bar chart series}
26 * var store = Ext.create('Ext.data.JsonStore', {
27 * fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
29 * {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
30 * {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
31 * {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
32 * {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
33 * {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
37 * Ext.create('Ext.chart.Chart', {
38 * renderTo: Ext.getBody(),
48 * renderer: Ext.util.Format.numberRenderer('0,0')
50 * title: 'Sample Values',
57 * title: 'Sample Metrics'
67 * renderer: function(storeItem, item) {
68 * this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
72 * display: 'insideEnd',
74 * renderer: Ext.util.Format.numberRenderer('0'),
75 * orientation: 'horizontal',
77 * 'text-anchor': 'middle'
84 * In this configuration we set `bar` as the series type, bind the values of the bar to the bottom axis and set the
85 * xField or category field to the `name` parameter of the store. We also set `highlight` to true which enables smooth
86 * animations when bars are hovered. We also set some configuration for the bar labels to be displayed inside the bar,
87 * to display the information found in the `data1` property of each element store, to render a formated text with the
88 * `Ext.util.Format` we pass in, to have an `horizontal` orientation (as opposed to a vertical one) and we also set
89 * other styles like `color`, `text-anchor`, etc.
91 Ext.define('Ext.chart.series.Bar', {
93 /* Begin Definitions */
95 extend: 'Ext.chart.series.Cartesian',
97 alternateClassName: ['Ext.chart.BarSeries', 'Ext.chart.BarChart', 'Ext.chart.StackedBarChart'],
99 requires: ['Ext.chart.axis.Axis', 'Ext.fx.Anim'],
101 /* End Definitions */
106 <span id='Ext-chart-series-Bar-cfg-column'> /**
107 </span> * @cfg {Boolean} column Whether to set the visualization as column chart or horizontal bar chart.
111 <span id='Ext-chart-series-Bar-cfg-style'> /**
112 </span> * @cfg style Style properties that will override the theming series styles.
116 <span id='Ext-chart-series-Bar-cfg-gutter'> /**
117 </span> * @cfg {Number} gutter The gutter space between single bars, as a percentage of the bar width
121 <span id='Ext-chart-series-Bar-cfg-groupGutter'> /**
122 </span> * @cfg {Number} groupGutter The gutter space between groups of bars, as a percentage of the bar width
126 <span id='Ext-chart-series-Bar-cfg-xPadding'> /**
127 </span> * @cfg {Number} xPadding Padding between the left/right axes and the bars
131 <span id='Ext-chart-series-Bar-cfg-yPadding'> /**
132 </span> * @cfg {Number} yPadding Padding between the top/bottom axes and the bars
136 constructor: function(config) {
137 this.callParent(arguments);
139 surface = me.chart.surface,
140 shadow = me.chart.shadow,
142 Ext.apply(me, config, {
151 "stroke-width": 6,
152 "stroke-opacity": 0.05,
153 stroke: 'rgb(200, 200, 200)',
159 "stroke-width": 4,
160 "stroke-opacity": 0.1,
161 stroke: 'rgb(150, 150, 150)',
167 "stroke-width": 2,
168 "stroke-opacity": 0.15,
169 stroke: 'rgb(100, 100, 100)',
176 me.group = surface.getGroup(me.seriesId + '-bars');
178 for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
179 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
184 // @private sets the bar girth.
185 getBarGirth: function() {
187 store = me.chart.store,
189 ln = store.getCount(),
190 gutter = me.gutter / 100;
192 return (me.chart.chartBBox[column ? 'width' : 'height'] - me[column ? 'xPadding' : 'yPadding'] * 2) / (ln * (gutter + 1) - gutter);
195 // @private returns the gutters.
196 getGutters: function() {
199 gutter = Math.ceil(me[column ? 'xPadding' : 'yPadding'] + me.getBarGirth() / 2);
200 return me.column ? [gutter, 0] : [0, gutter];
203 // @private Get chart and data boundaries
204 getBounds: function() {
207 store = chart.substore || chart.store,
208 bars = [].concat(me.yField),
209 barsLen = bars.length,
210 groupBarsLen = barsLen,
211 groupGutter = me.groupGutter / 100,
213 xPadding = me.xPadding,
214 yPadding = me.yPadding,
215 stacked = me.stacked,
216 barWidth = me.getBarGirth(),
220 groupBarWidth, bbox, minY, maxY, axis, out,
221 scale, zero, total, rec, j, plus, minus;
226 //Skip excluded series
228 for (j = 0, total = me.__excludes.length; j < total; j++) {
229 if (me.__excludes[j]) {
236 axis = chart.axes.get(me.axis);
238 out = axis.calcEnds();
239 minY = out.from || axis.prevMin;
240 maxY = mmax(out.to || axis.prevMax, 0);
244 if (me.yField && !Ext.isNumber(minY)) {
245 axis = Ext.create('Ext.chart.axis.Axis', {
247 fields: [].concat(me.yField)
249 out = axis.calcEnds();
250 minY = out.from || axis.prevMin;
251 maxY = mmax(out.to || axis.prevMax, 0);
254 if (!Ext.isNumber(minY)) {
257 if (!Ext.isNumber(maxY)) {
260 scale = (column ? bbox.height - yPadding * 2 : bbox.width - xPadding * 2) / (maxY - minY);
261 groupBarWidth = barWidth / ((stacked ? 1 : groupBarsLen) * (groupGutter + 1) - groupGutter);
262 zero = (column) ? bbox.y + bbox.height - yPadding : bbox.x + xPadding;
266 store.each(function(record, i) {
267 total[0][i] = total[0][i] || 0;
268 total[1][i] = total[1][i] || 0;
269 for (j = 0; j < barsLen; j++) {
270 if (me.__excludes && me.__excludes[j]) {
273 rec = record.get(bars[j]);
274 total[+(rec > 0)][i] += mabs(rec);
277 total[+(maxY > 0)].push(mabs(maxY));
278 total[+(minY > 0)].push(mabs(minY));
279 minus = mmax.apply(math, total[0]);
280 plus = mmax.apply(math, total[1]);
281 scale = (column ? bbox.height - yPadding * 2 : bbox.width - xPadding * 2) / (plus + minus);
282 zero = zero + minus * scale * (column ? -1 : 1);
284 else if (minY / maxY < 0) {
285 zero = zero - minY * scale * (column ? -1 : 1);
291 groupBarsLen: groupBarsLen,
293 groupBarWidth: groupBarWidth,
298 signed: minY / maxY < 0,
304 // @private Build an array of paths for the chart
305 getPaths: function() {
308 store = chart.substore || chart.store,
309 bounds = me.bounds = me.getBounds(),
310 items = me.items = [],
311 gutter = me.gutter / 100,
312 groupGutter = me.groupGutter / 100,
313 animate = chart.animate,
316 enableShadows = chart.shadow,
317 shadowGroups = me.shadowGroups,
318 shadowAttributes = me.shadowAttributes,
319 shadowGroupsLn = shadowGroups.length,
321 xPadding = me.xPadding,
322 yPadding = me.yPadding,
323 stacked = me.stacked,
324 barsLen = bounds.barsLen,
325 colors = me.colorArrayStyle,
326 colorLength = colors && colors.length || 0,
331 j, yValue, height, totalDim, totalNegDim, bottom, top, hasShadow, barAttr, attrs, counter,
332 shadowIndex, shadow, sprite, offset, floorY;
334 store.each(function(record, i, total) {
335 bottom = bounds.zero;
340 for (j = 0, counter = 0; j < barsLen; j++) {
342 if (me.__excludes && me.__excludes[j]) {
345 yValue = record.get(bounds.bars[j]);
346 height = Math.round((yValue - ((bounds.minY < 0) ? 0 : bounds.minY)) * bounds.scale);
348 fill: colors[(barsLen > 1 ? j : 0) % colorLength]
353 width: mmax(bounds.groupBarWidth, 0),
354 x: (bbox.x + xPadding + i * bounds.barWidth * (1 + gutter) + counter * bounds.groupBarWidth * (1 + groupGutter) * !stacked),
359 // draw in reverse order
360 offset = (total - 1) - i;
362 height: mmax(bounds.groupBarWidth, 0),
363 width: height + (bottom == bounds.zero),
364 x: bottom + (bottom != bounds.zero),
365 y: (bbox.y + yPadding + offset * bounds.barWidth * (1 + gutter) + counter * bounds.groupBarWidth * (1 + groupGutter) * !stacked + 1)
371 barAttr.height = mabs(height);
373 barAttr.x = top + height;
374 barAttr.width = mabs(height);
379 top += height * (column ? -1 : 1);
381 bottom += height * (column ? -1 : 1);
383 totalDim += mabs(height);
385 totalNegDim += mabs(height);
388 barAttr.x = Math.floor(barAttr.x) + 1;
389 floorY = Math.floor(barAttr.y);
390 if (!Ext.isIE9 && barAttr.y > floorY) {
394 barAttr.width = Math.floor(barAttr.width);
395 barAttr.height = Math.floor(barAttr.height);
399 value: [record.get(me.xField), yValue],
401 point: column ? [barAttr.x + barAttr.width / 2, yValue >= 0 ? barAttr.y : barAttr.y + barAttr.height] :
402 [yValue >= 0 ? barAttr.x + barAttr.width : barAttr.x, barAttr.y + barAttr.height / 2]
404 // When resizing, reset before animating
405 if (animate && chart.resizing) {
409 width: barAttr.width,
415 height: barAttr.height
417 if (enableShadows && (stacked && !hasShadow || !stacked)) {
420 for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
421 shadow = shadowGroups[shadowIndex].getAt(stacked ? i : (i * barsLen + j));
423 shadow.setAttributes(attrs, true);
427 //update sprite position and width/height
428 sprite = group.getAt(i * barsLen + j);
430 sprite.setAttributes(attrs, true);
435 if (stacked && items.length) {
436 items[i * counter].totalDim = totalDim;
437 items[i * counter].totalNegDim = totalNegDim;
442 // @private render/setAttributes on the shadows
443 renderShadows: function(i, barAttr, baseAttrs, bounds) {
446 surface = chart.surface,
447 animate = chart.animate,
448 stacked = me.stacked,
449 shadowGroups = me.shadowGroups,
450 shadowAttributes = me.shadowAttributes,
451 shadowGroupsLn = shadowGroups.length,
452 store = chart.substore || chart.store,
457 shadowIndex, shadowBarAttr, shadow, totalDim, totalNegDim, j, rendererAttributes;
459 if ((stacked && (i % bounds.groupBarsLen === 0)) || !stacked) {
460 j = i / bounds.groupBarsLen;
462 for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
463 shadowBarAttr = Ext.apply({}, shadowAttributes[shadowIndex]);
464 shadow = shadowGroups[shadowIndex].getAt(stacked ? j : i);
465 Ext.copyTo(shadowBarAttr, barAttr, 'x,y,width,height');
467 shadow = surface.add(Ext.apply({
469 group: shadowGroups[shadowIndex]
470 }, Ext.apply({}, baseAttrs, shadowBarAttr)));
473 totalDim = items[i].totalDim;
474 totalNegDim = items[i].totalNegDim;
476 shadowBarAttr.y = zero - totalNegDim;
477 shadowBarAttr.height = totalDim;
480 shadowBarAttr.x = zero - totalNegDim;
481 shadowBarAttr.width = totalDim;
486 rendererAttributes = me.renderer(shadow, store.getAt(j), shadowBarAttr, i, store);
487 me.onAnimate(shadow, { to: rendererAttributes });
490 rendererAttributes = me.renderer(shadow, store.getAt(j), Ext.apply(shadowBarAttr, { hidden: true }), i, store);
491 shadow.setAttributes(rendererAttributes, true);
495 rendererAttributes = me.renderer(shadow, store.getAt(j), Ext.apply(shadowBarAttr, { hidden: false }), i, store);
496 shadow.setAttributes(rendererAttributes, true);
498 shadows.push(shadow);
504 <span id='Ext-chart-series-Bar-method-drawSeries'> /**
505 </span> * Draws the series for the current chart.
507 drawSeries: function() {
510 store = chart.substore || chart.store,
511 surface = chart.surface,
512 animate = chart.animate,
513 stacked = me.stacked,
515 enableShadows = chart.shadow,
516 shadowGroups = me.shadowGroups,
517 shadowGroupsLn = shadowGroups.length,
519 seriesStyle = me.seriesStyle,
520 items, ln, i, j, baseAttrs, sprite, rendererAttributes, shadowIndex, shadowGroup,
521 bounds, endSeriesStyle, barAttr, attrs, anim;
523 if (!store || !store.getCount()) {
527 //fill colors are taken from the colors array.
528 delete seriesStyle.fill;
529 endSeriesStyle = Ext.apply(seriesStyle, this.style);
530 me.unHighlightItem();
531 me.cleanHighlights();
537 baseAttrs = column ? {
545 // Create new or reuse sprites and animate/display
546 for (i = 0; i < ln; i++) {
547 sprite = group.getAt(i);
548 barAttr = items[i].attr;
551 items[i].shadows = me.renderShadows(i, barAttr, baseAttrs, bounds);
554 // Create a new sprite if needed (no height)
556 attrs = Ext.apply({}, baseAttrs, barAttr);
557 attrs = Ext.apply(attrs, endSeriesStyle || {});
558 sprite = surface.add(Ext.apply({}, {
564 rendererAttributes = me.renderer(sprite, store.getAt(i), barAttr, i, store);
565 sprite._to = rendererAttributes;
566 anim = me.onAnimate(sprite, { to: Ext.apply(rendererAttributes, endSeriesStyle) });
567 if (enableShadows && stacked && (i % bounds.barsLen === 0)) {
568 j = i / bounds.barsLen;
569 for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
570 anim.on('afteranimate', function() {
572 }, shadowGroups[shadowIndex].getAt(j));
577 rendererAttributes = me.renderer(sprite, store.getAt(i), Ext.apply(barAttr, { hidden: false }), i, store);
578 sprite.setAttributes(Ext.apply(rendererAttributes, endSeriesStyle), true);
580 items[i].sprite = sprite;
583 // Hide unused sprites
584 ln = group.getCount();
585 for (j = i; j < ln; j++) {
586 group.getAt(j).hide(true);
588 // Hide unused shadows
590 for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
591 shadowGroup = shadowGroups[shadowIndex];
592 ln = shadowGroup.getCount();
593 for (j = i; j < ln; j++) {
594 shadowGroup.getAt(j).hide(true);
601 // @private handled when creating a label.
602 onCreateLabel: function(storeItem, item, i, display) {
604 surface = me.chart.surface,
605 group = me.labelsGroup,
607 endLabelStyle = Ext.apply({}, config, me.seriesLabelStyle || {}),
609 return surface.add(Ext.apply({
612 }, endLabelStyle || {}));
615 // @private callback used when placing a label.
616 onPlaceLabel: function(label, storeItem, item, i, display, animate, j, index) {
617 // Determine the label's final position. Starts with the configured preferred value but
618 // may get flipped from inside to outside or vice-versa depending on space.
621 groupBarWidth = opt.groupBarWidth,
624 chartBBox = chart.chartBBox,
625 resizing = chart.resizing,
626 xValue = item.value[0],
627 yValue = item.value[1],
630 rotate = config.orientation == 'vertical',
631 field = [].concat(config.field),
632 format = config.renderer,
633 text = format(storeItem.get(field[index])),
634 size = me.getLabelSize(text),
636 height = size.height,
639 insideStart = 'insideStart',
640 insideEnd = 'insideEnd',
646 label.setAttributes({
651 if (display == outside) {
652 if (height + offsetY + attr.height > (yValue >= 0 ? zero - chartBBox.y : chartBBox.y + chartBBox.height - zero)) {
656 if (height + offsetY > attr.height) {
660 x = attr.x + groupBarWidth / 2;
661 y = display == insideStart ?
662 (zero + ((height / 2 + 3) * (yValue >= 0 ? -1 : 1))) :
663 (yValue >= 0 ? (attr.y + ((height / 2 + 3) * (display == outside ? -1 : 1))) :
664 (attr.y + attr.height + ((height / 2 + 3) * (display === outside ? 1 : -1))));
667 if (display == outside) {
668 if (width + offsetX + attr.width > (yValue >= 0 ? chartBBox.x + chartBBox.width - zero : zero - chartBBox.x)) {
673 if (width + offsetX > attr.width) {
677 x = display == insideStart ?
678 (zero + ((width / 2 + 5) * (yValue >= 0 ? 1 : -1))) :
679 (yValue >= 0 ? (attr.x + attr.width + ((width / 2 + 5) * (display === outside ? 1 : -1))) :
680 (attr.x + ((width / 2 + 5) * (display === outside ? -1 : 1))));
681 y = attr.y + groupBarWidth / 2;
697 if (animate && resizing) {
699 x = attr.x + attr.width / 2;
703 y = attr.y + attr.height / 2;
705 label.setAttributes({
710 label.setAttributes({
721 me.onAnimate(label, { to: finalAttr });
724 label.setAttributes(Ext.apply(finalAttr, {
731 * Gets the dimensions of a given bar label. Uses a single hidden sprite to avoid
732 * changing visible sprites.
735 getLabelSize: function(value) {
736 var tester = this.testerLabel,
738 endLabelStyle = Ext.apply({}, config, this.seriesLabelStyle || {}),
739 rotated = config.orientation === 'vertical',
743 tester = this.testerLabel = this.chart.surface.add(Ext.apply({
748 tester.setAttributes({
752 // Flip the width/height if rotated, as getBBox returns the pre-rotated dimensions
753 bbox = tester.getBBox();
757 width: rotated ? h : w,
758 height: rotated ? w : h
762 // @private used to animate label, markers and other sprites.
763 onAnimate: function(sprite, attr) {
765 return this.callParent(arguments);
768 isItemInPoint: function(x, y, item) {
769 var bbox = item.sprite.getBBox();
770 return bbox.x <= x && bbox.y <= y
771 && (bbox.x + bbox.width) >= x
772 && (bbox.y + bbox.height) >= y;
775 // @private hide all markers
776 hideAll: function() {
777 var axes = this.chart.axes;
778 if (!isNaN(this._index)) {
779 if (!this.__excludes) {
780 this.__excludes = [];
782 this.__excludes[this._index] = true;
784 axes.each(function(axis) {
790 // @private show all markers
791 showAll: function() {
792 var axes = this.chart.axes;
793 if (!isNaN(this._index)) {
794 if (!this.__excludes) {
795 this.__excludes = [];
797 this.__excludes[this._index] = false;
799 axes.each(function(axis) {
805 <span id='Ext-chart-series-Bar-method-getLegendColor'> /**
806 </span> * Returns a string with the color to be used for the series legend item.
809 getLegendColor: function(index) {
811 return me.colorArrayStyle[index % me.colorArrayStyle.length];