16

Flex 2 Charting with XML tutorial

Jan 8, 2008

Adobe Flex is not well documented (well, let's say information is hard to find). Even more so for the charting component for Flex Builder 2. Hereby a tutorial where we set up a column chart, import XML data and format the chart.

Update: Added formatting paragraph and the end result.

Setting up the project

  • Create a new Basic Flex Project called ‘ChartingTutorial'.
  • Switch to Design View in the workspace.
  • Drag a column chart from your components window on the workspace and name it ‘columnchart'.
  • Align the chart and legend, and play around with the width and height of your Flex Application.

Loading data

  • Before we load data, we need to have actual data. In your navigator window right click on your projects bin directory and create a new file. Name the file ‘stats.xml'.

    Add the following XML code to this file:

    <data>
        <row name="Q1">
            <expenses>64</expenses>
            <revenue>98</revenue>
            <profit>34</profit>
        </row>
        <row name="Q2">
            <expenses>68</expenses>
            <revenue>96</revenue>
            <profit>28</profit>
        </row>
    
        <row name="Q3">
            <expenses>62</expenses>
            <revenue>89</revenue>
            <profit>27</profit>
        </row>
        <row name="Q4">
            <expenses>68</expenses>
            <revenue>96</revenue>
            <profit>26</profit>
        </row>
    </data>
    
  • To load XML data we will use a HTTPService called 'dataRequest'. Open your main application MXML file (ChartingTutorial.mxml) and switch to source view.

  • Add the following code inside the mx:Application node:

    <mx:HTTPService id="dataRequest" url="stats.xml" result="dataRequestResultHandler(event);" fault="dataRequestFaultHandler(event);" />
    
    The attributes ‘result' and ‘fault' are respectively for handling the result of the request and handling errors. These attributes point to actionscript which we are going to add now.
  • Add the following code inside the mx:Application node:

    <mx:Script>
        <![CDATA[
            //Code to add.
        ]]>
    </mx:Script>
    
  • Within the script and CDATA tags add the following import statements:

    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.collections.ArrayCollection;
    
  • Next we define the handler functions being called by the HTTPService together with a bindable variable in which we will store the XML result data:

    [Bindable]
    private var stats:ArrayCollection;
    private function dataRequestResultHandler(event:ResultEvent):void {
        stats = event.result.data.row;
    }
    
    private function dataRequestFaultHandler(event:FaultEvent):void {
        Alert.show(event.fault.message);
    }
    
  • We need to send the data request. We will do this by adding a creation complete attribute to the mx:Application element:

    creationComplete="dataRequest.send()"
    

 

Inserting data

  • Now it's time to insert the data into the chart. Add a dataProvider attribute to your columnChart element pointing to the stats variable:

    dataProvider="{stats}"
    
  • If you look in the XML file you will see that every row contains expenses, revenue and profit data data. These need to be added as columnSeries in your columnChar. The yField values point to these childs in the XML line node.

    <mx:series>
        <mx:ColumnSeries displayName="Expenses" yField="expenses"/>
        <mx:ColumnSeries displayName="Revenue" yField="revenue"/>
        <mx:ColumnSeries displayName="Profit" yField="profit"/>
    </mx:series>
    
  • You can now run the application! You should some something similar to this:

  • The horizontal axis doesn't have the right description yet. The description data is also located in the XML file in the name attribute in the row nodes. Changing the description is done by adding a horizontal axis within the columnChart which pointing to the dataset stats and the attribute name:

    <mx:horizontalAxis>
        <mx:CategoryAxis dataProvider="{stats}" categoryField="name"/>
    </mx:horizontalAxis>
    

 

Formating the chart
We are going to change the charts looks into a clean and smooth chart.

  • A Flex application background is always a gradient. In our case we will change it to a white background. It can be done in Design view, but changing it manually is also peanuts. Add the following attribute to the mx:Application node:

    backgroundGradientColors="[#ffffff, #ffffff]"
    
  • The shadow doesn't really fit in a clean and smooth appearance. To lose it we need to overrule the standard 'filter array' with an empty array by adding this bit code inside the mx:ColumnChart node

    <mx:seriesFilters><mx:Array/></mx:seriesFilters>
    
  • Let's lose those ugly huge horizontal and vertical axis. This is done by a axisRenderer element for both axis. Add the following code inside the mx:ColumnChart node:

    <mx:horizontalAxisRenderer>
        <mx:AxisRenderer>
            <mx:axisStroke>
                <mx:Stroke color="#999999" weight="1"/>
            </mx:axisStroke>
        </mx:AxisRenderer>
    </mx:horizontalAxisRenderer>
    
    <mx:verticalAxisRenderer>
        <mx:AxisRenderer>
            <mx:axisStroke>
                <mx:Stroke color="#999999" weight="1"/>
            </mx:axisStroke>
        </mx:AxisRenderer>
    </mx:verticalAxisRenderer>
    
  • The bars need some new colors too! Maybe nice blue tints?
    This is done by adding fill elements within the mx:ColumnSeries nodes. To make it easy for you, just replace the complete mx:Series element with this code:

    <mx:series>
        <mx:ColumnSeries displayName="Expenses" yField="expenses">
            <mx:fill>
                <mx:SolidColor color="#738994"/>
            </mx:fill>
        </mx:ColumnSeries>
        <mx:ColumnSeries displayName="Revenue" yField="revenue">
            <mx:fill>
                <mx:SolidColor color="#a7c8d8"/>
            </mx:fill>
        </mx:ColumnSeries>
        <mx:ColumnSeries displayName="Profit" yField="profit">
            <mx:fill>
                <mx:SolidColor color="#406374"/>
            </mx:fill>
        </mx:ColumnSeries>
    </mx:series>
    

Et violà. Behold my result:

Combine it with dynamic XML data and you will have a powerful chart.

Add comment +

Comments (16)

Marius
Jan 10, 2008
Thanks Face: Grin I've been indeed searching my ass off for some stuff (loading actual XML data in particular)
Ed
Mar 7, 2008
Thank you. That was my first step getting to grips with Flex charting.
Cyberthug
May 29, 2008
The code didn't work in Flex 3. I get a parse error on the binding.
rcz
Jun 2, 2008
The code didn't work in Flex 3. I get a parse error on the binding.
The tutorial is written for Flex version 2. When I have the time I'll try to make an updated version.
Brian
Jun 6, 2008
Face: Devil Grin
Fernanda Gomez
Jun 7, 2008
Great tutorial, thanks!
manjul
Jul 9, 2008
It really helped me......It works fine with FLEX 3.0 as well, just take out fault="dataRequestFaultHandler(event);"

Add for chart legend :
<mx:Legend dataProvider="{columnchart}"/>

Thanks
John Myers
Jul 23, 2008
Flex 3 fix:

1. Right click on your project folder in the Flex Navigator and click Properties.
2. Click on Flex Compiler
3. In the input for Additional compiler arguments, enter -use-network=false
hsTed
Jul 26, 2008
Your tutorial helped me to accomplish a tough project. thanks!
riyas
Aug 25, 2008
how to draw a area chart according to the input given by user in text box ?
karol
Nov 19, 2008
It's really great tutorial. But I have one question... what if I would like to add one more action (go to some URL after click on some column)?

I would like to have one more tag (<url> for example) in all 'row' tags and then go to url from this tag after click on column which is represented by this row? Could anyone please help me to do this kind of thing?
ssd
Aug 4, 2009
Face: Happy Face: Laughing Face: Sad Face: Crying Face: Devil Grin Face: Glasses Face: Grin Face: Kiss Face: Shocked Face: Wink Face: Monkey Face: Angel
ziruela
Sep 28, 2009
LALALALA
pLuM ♥
Sep 28, 2009
Face: Shocked
very interesting tutorial...
Face: Glasses
Matt
Nov 9, 2009
Thanks for this tutorial !!Face: Happy
Rekha.V
Mar 11, 2010
GOOD

Add comment

Message
Name
Confirmation code
Confirmation code