Flex: Stacked column chart – programmatically in actionscript

I was looking for ages for an example of a dynamically generated stacked column chart in Flex, but most of the examples were incorporating some MXML, or contained hard-coded series objects.  

The example below is based on Adobe Livedocs, but I show how to generate the series arrays programatically in as3, with no use of mxml code, and apply these series to a column chart (added to panelActionscript as seen in the code below). Also, this could be easily adapted to a barchart.

If youve got any suggestions, let me know.

Flex Stacked Chart

 

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()" width="622" height="660">
  <mx:Script><![CDATA[

  	 import mx.charts.CategoryAxis;
  	 import mx.charts.series.ColumnSeries;
  	 import mx.charts.ColumnChart;
  	 import mx.charts.series.ColumnSet;
     import mx.charts.Legend;
     import mx.charts.BarChart;
     import mx.charts.series.BarSet;
     import mx.charts.series.BarSeries;
     import mx.collections.ArrayCollection;

     [Bindable]
     private var yearlyData:ArrayCollection = new ArrayCollection([
        {month:"January", revenue:120, costs:45,
            overhead:102, oneTime:23},
        {month:"February", revenue:108, costs:42,
            overhead:87, oneTime:47},
        {month:"March", revenue:150, costs:82,
            overhead:32, oneTime:21},
        {month:"April", revenue:170, costs:44,
            overhead:68},
        {month:"May", revenue:250, costs:57,
            overhead:77, oneTime:17},
        {month:"June", revenue:200, costs:33,
            overhead:51, oneTime:30},
        {month:"July", revenue:145, costs:80,
            overhead:62, oneTime:18},
        {month:"August", revenue:166, costs:87,
            overhead:48},
        {month:"September", revenue:103, costs:56,
            overhead:42},
        {month:"October", revenue:140, costs:91,
            overhead:45, oneTime:60},
        {month:"November", revenue:100, costs:42,
            overhead:33, oneTime:67},
        {month:"December", revenue:182, costs:56,
            overhead:25, oneTime:48},
        {month:"May", revenue:120, costs:57,
            overhead:30}
     ]);

     private function initApp():void {

     	// Create a column chart object
        var stackedColumnChart:ColumnChart = new ColumnChart();
        stackedColumnChart.dataProvider = yearlyData;
        stackedColumnChart.showDataTips = true;
 stackedColumnChart.width	= 460;

 // Set the horizontal axix category
        var xAxis:CategoryAxis = new CategoryAxis();
        xAxis.categoryField = "month";
        stackedColumnChart.horizontalAxis = xAxis;

 // ColumnSet.series is an array which contains
 // an array of ColumnSeries objects.
        var columnSet:ColumnSet = new ColumnSet();
        columnSet.type = "stacked";

        // Each item in seriesDetails becomes a different segment of
        // a column in the stacked chart i.e. each item represents a series.
        var seriesDetails:ArrayCollection = new ArrayCollection([
        	{YField:"costs", DisplayName:"Recurring Costs"},
        	{YField:"overhead", DisplayName:"Overhead Costs"},
        	{YField:"oneTime", DisplayName:"One-Time Costs"}
        	]);

        // Create a ColumnSeries, and an array to be
        // populated with dynamically generated columnSeries objects
        var columnSeries:ColumnSeries;
    	var seriesArray:Array = new Array();

    	// Generate an array of ColumnSeries objects
        // which are then be applied to the ColumnSet series.
        for(var i:int = 0; i < seriesDetails.length; i++){
        	columnSeries = new ColumnSeries();
        	columnSeries.yField = seriesDetails[i].YField;
        	columnSeries.displayName = seriesDetails[i].DisplayName;
        	seriesArray.push(columnSeries);
        }
        columnSet.series = seriesArray;

 // c.series could take an array of column sets
 // for displaying mixed charts i.e. c.series = [columnSet1, columnSet2];
 stackedColumnChart.series = [columnSet];

        var legend:Legend = new Legend();
        legend.direction = "horizontal";
        legend.dataProvider = stackedColumnChart;

        panelActionscript.addChild(stackedColumnChart);
        panelActionscript.addChild(legend);

     }

  ]]></mx:Script>
  <mx:VBox height="100%">
    <mx:Panel title="Stacked chart (dynamically created in ActionScript)"
    				id="panelActionscript" width="490">
    </mx:Panel>
  </mx:VBox>
  <mx:Panel title="Same chart created solely in MXML" id="panelMxml" width="490">
    <mx:ColumnChart id="mxmlColumnChart" dataProvider="{yearlyData}"
    				showDataTips="true" width="470">
      <mx:horizontalAxis>
           <mx:CategoryAxis categoryField="month"/>
       </mx:horizontalAxis>
       <mx:series>
           <mx:ColumnSet type="stacked">
               <mx:ColumnSeries
                   yField="costs"
                   displayName="Recurring Costs"/>
               <mx:ColumnSeries
                   yField="overhead"
                   displayName="Overhead Costs"/>
               <mx:ColumnSeries
                   yField="oneTime"
                   displayName="One-Time Costs"/>
           </mx:ColumnSet>
       </mx:series>
    </mx:ColumnChart>
    <mx:Legend dataProvider="{mxmlColumnChart}" direction="horizontal"/>
  </mx:Panel>
</mx:WindowedApplication>

Advertisements

Tags: , , , , , ,

14 Responses to “Flex: Stacked column chart – programmatically in actionscript”

  1. DD Says:

    This is extremely well done and documented. Thank you so much for spending the time!!

  2. Rahim Naik Says:

    If you can do it with mxml you can do it with AS also. 🙂

  3. Brian Bishop Says:

    Just change WindowedApplication to Application to run in Browser (is set to run as Air App)

  4. Jude Says:

    Hi
    Thanks alot for your nice modification from livedocs. Which you made to draw series auto.

    Thanks for your support

  5. Satya Says:

    Bishop,
    Thanks for sharing this, it is awesome.
    Can you please tell me how can i change the color of one of the series. i.e by default i want the color of the first series to be black.

    appreciate your help.

    -Sathya

  6. Brian Bishop Says:

    Hi Sathya

    I have answered your question on my new blog (I moved to my own hosting site – it has some better Flex examples too)

    http://bbishop.org/blog/?p=91#comment-107

  7. lekshmi Says:

    Hi Bishop,
    Could u plz give another version for this like we generate it via dynamic xml.how to retrieve this via xml to create stacked bar chart.

    thanks in advance

  8. Cecilia Says:

    s better to use whole foods made from scratch for good health.
    Anyone who dares to make a closer inspection will find the underlying difference.

    Many people don’t have the time to weight themselves every day, but checking the scale on a regular basis can definitely help when you’re working
    to lose weight and keep it off.

  9. Lester Says:

    If you find it a bit maddening to follow the daily fluctuations
    of the scale even though you are eating properly,
    pick three days of the week on which you will always weigh yourself (for example,
    Monday, Wednesday, and Friday). Anyone who dares to make a closer inspection will find
    the underlying difference. That way, the actual process will
    end up being much less frustrating and, for the majority of people,
    enjoyable.

  10. stagepolonia2011.xoom.it Says:

    a Bruce Lee workout includes stretching, bending, running, dipping, kicking, jumping, traditional muscle building exercises, weight lifting, rope skipping,
    medicine ball handling, etc. Vitamin B3 or also called as
    Niacin is important in weight loss because it is responsible for
    the regulation of thyroid hormones and also in sugar levels in the body.

    Then leave it a while until your tummy lets you know that you’re hungry again before opting for a healthy snack.

  11. fun kinder und jugendreisen Says:

    Have flexibility in work: Having flexibility in work schedules of employees will
    surely make them relaxed. There was something indescribable that seemed to call to me.

    Many carriers offer their customers the option of viewing specialized mobile channels.

  12. best protein powder Says:

    A fascinating discussion is definitely worth comment. I believe that
    you ought to publish more on this topic, it may not be a taboo matter but generally
    people don’t discuss such subjects. To the next!
    Cheers!!

  13. cheap Auction sites Says:

    Hello there! I know this is kind of off topic but I was wondering which blog
    platform are you using for this site? I’m getting sick and tired of WordPress because
    I’ve had problems with hackers and I’m looking at alternatives for another platform.
    I would be great if you could point me in the direction of a good platform.

  14. fast muscle building Says:

    Thanks for sharing your thoughts on loss results.

    Regards

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: