1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-chart.series.Pie'>/**
2 </span> * @class Ext.chart.series.Pie
3 * @extends Ext.chart.series.Series
5 * Creates a Pie Chart. A Pie Chart is a useful visualization technique to display quantitative information for different
6 * categories that also have a meaning as a whole.
7 * As with all other series, the Pie Series must be appended in the *series* Chart array configuration. See the Chart
8 * documentation for more information. A typical configuration object for the pie series could be:
10 * {@img Ext.chart.series.Pie/Ext.chart.series.Pie.png Ext.chart.series.Pie chart series}
12 * var store = Ext.create('Ext.data.JsonStore', {
13 * fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
15 * {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
16 * {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
17 * {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
18 * {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
19 * {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
23 * Ext.create('Ext.chart.Chart', {
24 * renderTo: Ext.getBody(),
29 * theme: 'Base:gradients',
38 * renderer: function(storeItem, item) {
39 * //calculate and display percentage on hover
41 * store.each(function(rec) {
42 * total += rec.get('data1');
44 * this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data1') / total * 100) + '%');
61 * In this configuration we set `pie` as the type for the series, set an object with specific style properties for highlighting options
62 * (triggered when hovering elements). We also set true to `showInLegend` so all the pie slices can be represented by a legend item.
63 * We set `data1` as the value of the field to determine the angle span for each pie slice. We also set a label configuration object
64 * where we set the field name of the store field to be renderer as text for the label. The labels will also be displayed rotated.
65 * We set `contrast` to `true` to flip the color of the label if it is to similar to the background color. Finally, we set the font family
66 * and size through the `font` parameter.
70 Ext.define('Ext.chart.series.Pie', {
72 /* Begin Definitions */
74 alternateClassName: ['Ext.chart.PieSeries', 'Ext.chart.PieChart'],
76 extend: 'Ext.chart.series.Series',
80 type: "pie",
86 <span id='Ext-chart.series.Pie-cfg-highlightDuration'> /**
87 </span> * @cfg {Number} highlightDuration
88 * The duration for the pie slice highlight effect.
90 highlightDuration: 150,
92 <span id='Ext-chart.series.Pie-cfg-angleField'> /**
93 </span> * @cfg {String} angleField
94 * The store record field name to be used for the pie angles.
95 * The values bound to this field name must be positive real numbers.
96 * This parameter is required.
100 <span id='Ext-chart.series.Pie-cfg-lengthField'> /**
101 </span> * @cfg {String} lengthField
102 * The store record field name to be used for the pie slice lengths.
103 * The values bound to this field name must be positive real numbers.
104 * This parameter is optional.
108 <span id='Ext-chart.series.Pie-cfg-donut'> /**
109 </span> * @cfg {Boolean|Number} donut
110 * Whether to set the pie chart as donut chart.
111 * Default's false. Can be set to a particular percentage to set the radius
112 * of the donut chart.
116 <span id='Ext-chart.series.Pie-cfg-showInLegend'> /**
117 </span> * @cfg {Boolean} showInLegend
118 * Whether to add the pie chart elements as legend items. Default's false.
122 <span id='Ext-chart.series.Pie-cfg-colorSet'> /**
123 </span> * @cfg {Array} colorSet
124 * An array of color values which will be used, in order, as the pie slice fill colors.
127 <span id='Ext-chart.series.Pie-cfg-style'> /**
128 </span> * @cfg {Object} style
129 * An object containing styles for overriding series styles from Theming.
133 constructor: function(config) {
134 this.callParent(arguments);
137 surface = chart.surface,
139 shadow = chart.shadow, i, l, cfg;
147 Ext.apply(me, config, {
149 "stroke-width": 6,
150 "stroke-opacity": 1,
151 stroke: 'rgb(200, 200, 200)',
158 "stroke-width": 4,
159 "stroke-opacity": 1,
160 stroke: 'rgb(150, 150, 150)',
167 "stroke-width": 2,
168 "stroke-opacity": 1,
169 stroke: 'rgb(100, 100, 100)',
176 me.group = surface.getGroup(me.seriesId);
178 for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
179 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
182 surface.customAttributes.segment = function(opt) {
183 return me.getSegment(opt);
187 //@private updates some onbefore render parameters.
188 initialize: function() {
190 store = me.chart.substore || me.chart.store;
191 //Add yFields to be used in Legend.js
193 if (me.label.field) {
194 store.each(function(rec) {
195 me.yField.push(rec.get(me.label.field));
200 // @private returns an object with properties for a PieSlice.
201 getSegment: function(opt) {
209 x1 = 0, x2 = 0, x3 = 0, x4 = 0,
210 y1 = 0, y2 = 0, y3 = 0, y4 = 0,
212 r = opt.endRho - opt.startRho,
213 startAngle = opt.startAngle,
214 endAngle = opt.endAngle,
215 midAngle = (startAngle + endAngle) / 2 * rad,
216 margin = opt.margin || 0,
217 flag = abs(endAngle - startAngle) > 180,
218 a1 = Math.min(startAngle, endAngle) * rad,
219 a2 = Math.max(startAngle, endAngle) * rad,
222 x += margin * cos(midAngle);
223 y += margin * sin(midAngle);
225 x1 = x + opt.startRho * cos(a1);
226 y1 = y + opt.startRho * sin(a1);
228 x2 = x + opt.endRho * cos(a1);
229 y2 = y + opt.endRho * sin(a1);
231 x3 = x + opt.startRho * cos(a2);
232 y3 = y + opt.startRho * sin(a2);
234 x4 = x + opt.endRho * cos(a2);
235 y4 = y + opt.endRho * sin(a2);
237 if (abs(x1 - x3) <= delta && abs(y1 - y3) <= delta) {
240 //Solves mysterious clipping bug with IE
244 ["M", x1, y1],
245 ["L", x2, y2],
246 ["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
252 ["M", x1, y1],
253 ["L", x2, y2],
254 ["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
255 ["L", x3, y3],
256 ["A", opt.startRho, opt.startRho, 0, +flag, 0, x1, y1],
262 // @private utility function to calculate the middle point of a pie slice.
263 calcMiddle: function(item) {
269 startAngle = slice.startAngle,
270 endAngle = slice.endAngle,
272 a1 = Math.min(startAngle, endAngle) * rad,
273 a2 = Math.max(startAngle, endAngle) * rad,
274 midAngle = -(a1 + (a2 - a1) / 2),
275 xm = x + (item.endRho + item.startRho) / 2 * Math.cos(midAngle),
276 ym = y - (item.endRho + item.startRho) / 2 * Math.sin(midAngle);
284 <span id='Ext-chart.series.Pie-method-drawSeries'> /**
285 </span> * Draws the series for the current chart.
287 drawSeries: function() {
289 store = me.chart.substore || me.chart.store,
291 animate = me.chart.animate,
292 field = me.angleField || me.field || me.xField,
293 lenField = [].concat(me.lengthField),
295 colors = me.colorSet,
297 surface = chart.surface,
298 chartBBox = chart.chartBBox,
299 enableShadows = chart.shadow,
300 shadowGroups = me.shadowGroups,
301 shadowAttributes = me.shadowAttributes,
302 lnsh = shadowGroups.length,
304 layers = lenField.length,
317 seriesStyle = me.seriesStyle,
318 seriesLabelStyle = me.seriesLabelStyle,
319 colorArrayStyle = me.colorArrayStyle,
320 colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
321 gutterX = chart.maxGutter[0],
322 gutterY = chart.maxGutter[1],
351 Ext.apply(seriesStyle, me.style || {});
356 //override theme colors
358 colorArrayStyle = me.colorSet;
359 colorArrayLength = colorArrayStyle.length;
362 //if not store or store is empty then there's nothing to draw
363 if (!store || !store.getCount()) {
367 me.unHighlightItem();
368 me.cleanHighlights();
370 centerX = me.centerX = chartBBox.x + (chartBBox.width / 2);
371 centerY = me.centerY = chartBBox.y + (chartBBox.height / 2);
372 me.radius = Math.min(centerX - chartBBox.x, centerY - chartBBox.y);
373 me.slices = slices = [];
374 me.items = items = [];
376 store.each(function(record, i) {
377 if (this.__excludes && this.__excludes[i]) {
381 totalField += +record.get(field);
383 for (j = 0, totalLenField = 0; j < layers; j++) {
384 totalLenField += +record.get(lenField[j]);
386 layerTotals[i] = totalLenField;
387 maxLenField = Math.max(maxLenField, totalLenField);
391 store.each(function(record, i) {
392 if (this.__excludes && this.__excludes[i]) {
396 value = record.get(field);
397 middleAngle = angle - 360 * value / totalField / 2;
398 // TODO - Put up an empty circle
399 if (isNaN(middleAngle)) {
405 if (!i || first == 0) {
406 angle = 360 - middleAngle;
407 me.firstAngle = angle;
408 middleAngle = angle - 360 * value / totalField / 2;
410 endAngle = angle - 360 * value / totalField;
419 lenValue = layerTotals[i];
420 slice.rho = me.radius * (lenValue / maxLenField);
422 slice.rho = me.radius;
425 if((slice.startAngle % 360) == (slice.endAngle % 360)) {
426 slice.startAngle -= 0.0001;
432 //do all shadows first.
434 for (i = 0, ln = slices.length; i < ln; i++) {
435 if (this.__excludes && this.__excludes[i]) {
440 slice.shadowAttrs = [];
441 for (j = 0, rhoAcum = 0, shadows = []; j < layers; j++) {
442 sprite = group.getAt(i * layers + j);
443 deltaRho = lenField[j] ? store.getAt(i).get(lenField[j]) / layerTotals[i] * slice.rho: slice.rho;
444 //set pie slice properties
445 rendererAttributes = {
447 startAngle: slice.startAngle,
448 endAngle: slice.endAngle,
451 startRho: rhoAcum + (deltaRho * donut / 100),
452 endRho: rhoAcum + deltaRho
456 for (shindex = 0, shadows = []; shindex < lnsh; shindex++) {
457 shadowAttr = shadowAttributes[shindex];
458 shadow = shadowGroups[shindex].getAt(i);
460 shadow = chart.surface.add(Ext.apply({},
463 group: shadowGroups[shindex],
464 strokeLinejoin: "round"
466 rendererAttributes, shadowAttr));
469 rendererAttributes = me.renderer(shadow, store.getAt(i), Ext.apply({},
470 rendererAttributes, shadowAttr), i, store);
471 me.onAnimate(shadow, {
472 to: rendererAttributes
475 rendererAttributes = me.renderer(shadow, store.getAt(i), Ext.apply(shadowAttr, {
478 shadow.setAttributes(rendererAttributes, true);
480 shadows.push(shadow);
482 slice.shadowAttrs[j] = shadows;
486 //do pie slices after.
487 for (i = 0, ln = slices.length; i < ln; i++) {
488 if (this.__excludes && this.__excludes[i]) {
493 for (j = 0, rhoAcum = 0; j < layers; j++) {
494 sprite = group.getAt(i * layers + j);
495 deltaRho = lenField[j] ? store.getAt(i).get(lenField[j]) / layerTotals[i] * slice.rho: slice.rho;
496 //set pie slice properties
497 rendererAttributes = Ext.apply({
499 startAngle: slice.startAngle,
500 endAngle: slice.endAngle,
503 startRho: rhoAcum + (deltaRho * donut / 100),
504 endRho: rhoAcum + deltaRho
506 }, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[(layers > 1? j : i) % colorArrayLength] } || {}));
508 rendererAttributes.segment, {
511 storeItem: slice.storeItem,
516 item.shadows = slice.shadowAttrs[j];
519 // Create a new sprite if needed (no height)
521 spriteOptions = Ext.apply({
522 type: "path",
525 }, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[(layers > 1? j : i) % colorArrayLength] } || {}));
526 sprite = surface.add(Ext.apply(spriteOptions, rendererAttributes));
528 slice.sprite = slice.sprite || [];
529 item.sprite = sprite;
530 slice.sprite.push(sprite);
531 slice.point = [item.middle.x, item.middle.y];
533 rendererAttributes = me.renderer(sprite, store.getAt(i), rendererAttributes, i, store);
534 sprite._to = rendererAttributes;
535 sprite._animating = true;
536 me.onAnimate(sprite, {
537 to: rendererAttributes,
541 this._animating = false;
548 rendererAttributes = me.renderer(sprite, store.getAt(i), Ext.apply(rendererAttributes, {
551 sprite.setAttributes(rendererAttributes, true);
558 ln = group.getCount();
559 for (i = 0; i < ln; i++) {
560 if (!slices[(i / layers) >> 0] && group.getAt(i)) {
561 group.getAt(i).hide(true);
565 lnsh = shadowGroups.length;
566 for (shindex = 0; shindex < ln; shindex++) {
567 if (!slices[(shindex / layers) >> 0]) {
568 for (j = 0; j < lnsh; j++) {
569 if (shadowGroups[j].getAt(shindex)) {
570 shadowGroups[j].getAt(shindex).hide(true);
580 // @private callback for when creating a label sprite.
581 onCreateLabel: function(storeItem, item, i, display) {
583 group = me.labelsGroup,
585 centerX = me.centerX,
586 centerY = me.centerY,
587 middle = item.middle,
588 endLabelStyle = Ext.apply(me.seriesLabelStyle || {}, config || {});
590 return me.chart.surface.add(Ext.apply({
592 'text-anchor': 'middle',
599 // @private callback for when placing a label sprite.
600 onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {
603 resizing = chart.resizing,
605 format = config.renderer,
606 field = [].concat(config.field),
607 centerX = me.centerX,
608 centerY = me.centerY,
609 middle = item.middle,
614 x = middle.x - centerX,
615 y = middle.y - centerY,
618 theta = Math.atan2(y, x || 1),
619 dg = theta * 180 / Math.PI,
622 function fixAngle(a) {
623 if (a < 0) a += 360;
627 label.setAttributes({
628 text: format(storeItem.get(field[index]))
633 rho = Math.sqrt(x * x + y * y) * 2;
635 opt.x = rho * Math.cos(theta) + centerX;
636 opt.y = rho * Math.sin(theta) + centerY;
641 dg = (dg > 90 && dg < 270) ? dg + 180: dg;
643 prevDg = label.attr.rotation.degrees;
644 if (prevDg != null && Math.abs(prevDg - dg) > 180) {
645 if (dg > prevDg) {
654 //update rotation angle
665 //ensure the object has zero translation
669 if (animate && !resizing && (display != 'rotate' || prevDg != null)) {
670 me.onAnimate(label, {
674 label.setAttributes(opt, true);
679 // @private callback for when placing a callout sprite.
680 onPlaceCallout: function(callout, storeItem, item, i, display, animate, index) {
683 resizing = chart.resizing,
684 config = me.callouts,
685 centerX = me.centerX,
686 centerY = me.centerY,
687 middle = item.middle,
692 x = middle.x - centerX,
693 y = middle.y - centerY,
696 theta = Math.atan2(y, x || 1),
697 bbox = callout.label.getBBox(),
703 //should be able to config this.
704 rho = item.endRho + offsetFromViz;
705 rhoCenter = (item.endRho + item.startRho) / 2 + (item.endRho - item.startRho) / 3;
707 opt.x = rho * Math.cos(theta) + centerX;
708 opt.y = rho * Math.sin(theta) + centerY;
710 x = rhoCenter * Math.cos(theta);
711 y = rhoCenter * Math.sin(theta);
714 //set the line from the middle of the pie to the box.
715 me.onAnimate(callout.lines, {
717 path: ["M", x + centerX, y + centerY, "L", opt.x, opt.y, "Z", "M", opt.x, opt.y, "l", x > 0 ? offsetToSide: -offsetToSide, 0, "z"]
721 me.onAnimate(callout.box, {
723 x: opt.x + (x > 0 ? offsetToSide: -(offsetToSide + bbox.width + 2 * offsetBox)),
724 y: opt.y + (y > 0 ? ( - bbox.height - offsetBox / 2) : ( - bbox.height - offsetBox / 2)),
725 width: bbox.width + 2 * offsetBox,
726 height: bbox.height + 2 * offsetBox
730 me.onAnimate(callout.label, {
732 x: opt.x + (x > 0 ? (offsetToSide + offsetBox) : -(offsetToSide + bbox.width + offsetBox)),
733 y: opt.y + (y > 0 ? -bbox.height / 4: -bbox.height / 4)
737 //set the line from the middle of the pie to the box.
738 callout.lines.setAttributes({
739 path: ["M", x + centerX, y + centerY, "L", opt.x, opt.y, "Z", "M", opt.x, opt.y, "l", x > 0 ? offsetToSide: -offsetToSide, 0, "z"]
743 callout.box.setAttributes({
744 x: opt.x + (x > 0 ? offsetToSide: -(offsetToSide + bbox.width + 2 * offsetBox)),
745 y: opt.y + (y > 0 ? ( - bbox.height - offsetBox / 2) : ( - bbox.height - offsetBox / 2)),
746 width: bbox.width + 2 * offsetBox,
747 height: bbox.height + 2 * offsetBox
751 callout.label.setAttributes({
752 x: opt.x + (x > 0 ? (offsetToSide + offsetBox) : -(offsetToSide + bbox.width + offsetBox)),
753 y: opt.y + (y > 0 ? -bbox.height / 4: -bbox.height / 4)
758 callout[p].show(true);
762 // @private handles sprite animation for the series.
763 onAnimate: function(sprite, attr) {
765 return this.callParent(arguments);
768 isItemInPoint: function(x, y, item, i) {
775 startAngle = item.startAngle,
776 endAngle = item.endAngle,
777 rho = Math.sqrt(dx * dx + dy * dy),
778 angle = Math.atan2(y - cy, x - cx) / me.rad + 360;
780 // normalize to the same range of angles created by drawSeries
781 if (angle > me.firstAngle) {
784 return (angle <= startAngle && angle > endAngle
785 && rho >= item.startRho && rho <= item.endRho);
788 // @private hides all elements in the series.
789 hideAll: function() {
790 var i, l, shadow, shadows, sh, lsh, sprite;
791 if (!isNaN(this._index)) {
792 this.__excludes = this.__excludes || [];
793 this.__excludes[this._index] = true;
794 sprite = this.slices[this._index].sprite;
795 for (sh = 0, lsh = sprite.length; sh < lsh; sh++) {
796 sprite[sh].setAttributes({
800 if (this.slices[this._index].shadowAttrs) {
801 for (i = 0, shadows = this.slices[this._index].shadowAttrs, l = shadows.length; i < l; i++) {
803 for (sh = 0, lsh = shadow.length; sh < lsh; sh++) {
804 shadow[sh].setAttributes({
814 // @private shows all elements in the series.
815 showAll: function() {
816 if (!isNaN(this._index)) {
817 this.__excludes[this._index] = false;
822 <span id='Ext-chart.series.Pie-method-highlightItem'> /**
823 </span> * Highlight the specified item. If no item is provided the whole series will be highlighted.
824 * @param item {Object} Info about the item; same format as returned by #getItemForPoint
826 highlightItem: function(item) {
829 item = item || this.items[this._index];
831 //TODO(nico): sometimes in IE itemmouseover is triggered
832 //twice without triggering itemmouseout in between. This
833 //fixes the highlighting bug. Eventually, events should be
834 //changed to trigger one itemmouseout between two itemmouseovers.
835 this.unHighlightItem();
837 if (!item || item.sprite && item.sprite._animating) {
840 me.callParent([item]);
844 if ('segment' in me.highlightCfg) {
845 var highlightSegment = me.highlightCfg.segment,
846 animate = me.chart.animate,
847 attrs, i, shadows, shadow, ln, to, itemHighlightSegment, prop;
849 if (me.labelsGroup) {
850 var group = me.labelsGroup,
851 display = me.label.display,
852 label = group.getAt(item.index),
853 middle = (item.startAngle + item.endAngle) / 2 * rad,
854 r = highlightSegment.margin || 0,
855 x = r * Math.cos(middle),
856 y = r * Math.sin(middle);
858 //TODO(nico): rounding to 1e-10
859 //gives the right translation. Translation
860 //was buggy for very small numbers. In this
861 //case we're not looking to translate to very small
862 //numbers but not to translate at all.
863 if (Math.abs(x) < 1e-10) {
866 if (Math.abs(y) < 1e-10) {
871 label.stopAnimation();
879 duration: me.highlightDuration
883 label.setAttributes({
892 if (me.chart.shadow && item.shadows) {
894 shadows = item.shadows;
896 for (; i < ln; i++) {
899 itemHighlightSegment = item.sprite._from.segment;
900 for (prop in itemHighlightSegment) {
901 if (! (prop in highlightSegment)) {
902 to[prop] = itemHighlightSegment[prop];
906 segment: Ext.applyIf(to, me.highlightCfg.segment)
909 shadow.stopAnimation();
912 duration: me.highlightDuration
916 shadow.setAttributes(attrs, true);
923 <span id='Ext-chart.series.Pie-method-unHighlightItem'> /**
924 </span> * un-highlights the specified item. If no item is provided it will un-highlight the entire series.
925 * @param item {Object} Info about the item; same format as returned by #getItemForPoint
927 unHighlightItem: function() {
933 if (('segment' in me.highlightCfg) && me.items) {
934 var items = me.items,
935 animate = me.chart.animate,
936 shadowsEnabled = !!me.chart.shadow,
937 group = me.labelsGroup,
941 display = me.label.display,
942 shadowLen, p, to, ihs, hs, sprite, shadows, shadow, item, label, attrs;
944 for (; i < len; i++) {
949 sprite = item.sprite;
950 if (sprite && sprite._highlighted) {
953 label = group.getAt(item.index);
960 display == 'rotate' ? {
964 degrees: label.attr.rotation.degrees
968 label.stopAnimation();
971 duration: me.highlightDuration
975 label.setAttributes(attrs, true);
978 if (shadowsEnabled) {
979 shadows = item.shadows;
980 shadowLen = shadows.length;
981 for (; j < shadowLen; j++) {
983 ihs = item.sprite._to.segment;
984 hs = item.sprite._from.segment;
993 shadow.stopAnimation();
998 duration: me.highlightDuration
1002 shadow.setAttributes({ segment: to }, true);
1009 me.callParent(arguments);
1012 <span id='Ext-chart.series.Pie-method-getLegendColor'> /**
1013 </span> * Returns the color of the series (to be displayed as color for the series legend item).
1014 * @param item {Object} Info about the item; same format as returned by #getItemForPoint
1016 getLegendColor: function(index) {
1018 return me.colorArrayStyle[index % me.colorArrayStyle.length];
1022 </pre></pre></body></html>