Gary Sieling

ExtJS Pie Chart Example

Problem

You want to display a pie chart.


Solution

Use the Ext.chart.Chart, and set several properties under the “series” property to render a pie chart.

Ext.onReady(function() {
    Ext.define('PopulationPoint', {
        extend: 'Ext.data.Model',
        fields: ['state', 'population']
    });

var store = Ext.create('Ext.data.Store', {
    model: 'PopulationPoint',
    data: [{ state:"Alabama", population: 4802740},
           { state:"Alaska", population: 722718},
           { state:"Arizona", population: 6482505},
           { state:"Arkansas", population: 2937979},
           { state:"California", population: 37691912},
           { state:"Colorado", population: 5116796},
           { state:"Connecticut", population: 3580709},
           { state:"Delaware", population: 907135},
           { state:"DC", population: 617996} ]
  });

  Ext.create('Ext.chart.Chart', {
     renderTo: Ext.getBody(),
     width: 470,
     height: 300,
     store: store,
     series: [
     {
       type: 'pie',
       field: 'population',
       label: {
         field: 'state',
         display: 'outside',
         font: '12px Arial'
       }
     }]
  });	
});

Discussion

To transform the line chart example into a pie chart, change the series type to ‘pie’, and remove the axes and series definition. Pie charts usually have two fields – a numeric value, and a label. The numeric value is set through the “field” property of the series. The label is an entire object, which has it’s own property called field- it’s a shame they were not able to use the axes properties of a chart to make the API more consistent.

Pie charts are fairly difficult to render well – too many records will look cramped, and overlapping text, as in my example, makes it difficult to read. Ext provides a number of options for controlling text rendering, as well as a “tips” properties on the series to add tooltips.

If you want to ensure that colors are drawn consistently, you must set the colorSet property, which is an array of colors. You must ensure that this has the same number of value as the pie chart data. There are two ways to do this – include zero valued entries in the store (although logically these will not render), or build the colorSet property value based on what values are included in the store.

See also
ExtJS Line Chart Example, ExtJS Tooltip Example, ExtJS xtemplate example

Exit mobile version