How to Make Charts with Flex 3
Flex makes actionscript less of a chore and more of a design asset. One of the best demonstrations of this is the simplicity of charting with MXML.
In this tutorial we’ll take test scores from XML files and make a dynamic bar graph out of the results in no time at all. You’ll have impressed yourself by the end.
Step 1 – A Note, An Offer, and the Setup
As you’ll quickly realize, I do not use the SDK to build Flex 3 files. While this tutorial is taught from the perspective of the Flex 3 Builder, the underlying code is the same. SDK users, you’ll simply have to substitute steps as needed. I won’t be using the design view in this tutorial, so you’re in luck.
If anyone with educational ties has yet to take advantage of the “Free Flex 3 for Education” deal yet, go ahead and do that now. It’ll help you out enormously.
Start up Flex 3 Builder and make a new MXML Application (File>New>MXML Application). You’ll be greeted with the window below. Give the application whichever name you’d like (I will be using ‘charts’) and set the layout to ‘vertical’. This will ensure that elements aren’t positioned on top of each other by default.

Step 2 – Connect the XML files
We will be loading data from two XML files for this tutorial. Each contains the SAT scores of three different students. From within your project’s ‘src’ folder create a new folder called ‘assets’. Download the XML files here and import them into the folder you just made. The basic structure of the XML is as follows.
<chart> <student> <name>John</name> <sat>1300</sat> </student> </chart>
As you can see we’ll be loading two pieces of information from each node; the student’s name and their SAT score. For a more in depth explanation of loading XML in Flex, I recommend taking a minute to look over this tutorial. Otherwise, begin by making the following HTTP Service component to load the XML under the opening application tag.
<mx:HTTPService url="assets/test-data.xml" id="testData" result="xmlHandler(event)" resultFormat="e4x"/>
We send this HTTP request using the creationComplete event in the application tag.
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="testData.send()">
With a bit of actionscript we’ll have the XML loaded and ready to work with. Insert a script tag immediately below the opening application tag and above the HTTP Service.
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
//XML List for loaded XML file. Must be bindable!
[Bindable]private var testInfo:XMLList;
private function xmlHandler(evt:ResultEvent):void{
//Sets testInfo's root as the student. Everything else referenced in respect to this.
testInfo = evt.result.student;
}
]]>
</mx:Script>
Step 3 – Build the Chart
Now that we have all this data at our fingertips, it would be nice to actually do something with it. Bring in the chart components! Put the following right below the HTTP Service tag.
<!--Contains page components. Design only-->
<mx:VBox horizontalAlign="center">
<!--Panel effects design only-->
<mx:Panel horizontalAlign="center" title="College Test Score Data">
<!--The Chart 'testChart'-->
<mx:ColumnChart dataProvider="{testInfo}" id="testChart" showDataTips="true">
<mx:horizontalAxis>
<mx:CategoryAxis dataProvider="{testInfo}" categoryField="name"/>
</mx:horizontalAxis>
<mx:series>
<mx:ColumnSeries xField="name" yField="sat" displayName="Sat Score"/>
</mx:series>
</mx:ColumnChart>
</mx:Panel>
<!--Legend for Chart Data-->
<mx:Legend dataProvider="{testChart}"/>
</mx:VBox>
It looks complicated, but let’s break it down to the basics:
- The VBox is used to contain and center the components it contains. It only serves as a design aide.
- The Panel is used to contain the chart and display a title. It only also only a design aide.
- The ColumnChart begins the Column charting component. There are multiple types of charts available (Pie, Bar, etc) and most work in the same way as the Column. Adobe has great documentation on the specifics.
The dataProvider field is bound to the XML List ‘testInfo’ we made earlier which contains the XML data. For more information on data binding, here is a tutorial that demonstrates the basics. Data tips are enabled and will display a tooltip like notification when the column is moused over.
- The horizontalAxis controls the information displayed along the x-axis. The CategoryAxis specifies the data source and field from data source to load from.
- The series tag contains the information that will be charted.
- ColumnSeries specifies which field (or node) from the XML file is displayed on each axis. The display name controls the label for the column’s information. While there is only one column in this example, adding additional ones is as simple as adding more ColumnSeries in series.
- The legend is bound to the ColumnChart component (named testChart) and will display the value of the each ColumnSeries’ displayName along with the color.
Step 4 – Switching Between Data
As you’ll recall, we have two different XML files worth of data for this chart. Currently, we’ve only loaded the first one (test-data.xml). We’ll use this as a way to demonstrate how easily Flex charts can adapt with data binding. To do this we’ll need to make a few modifications to the code we’ve written. Start by two buttons directly below the end of the ColumnChart. We will use these to change which XML file the data is being loaded from. I have encapsulated them in an HBox for design purposes only.
<mx:HBox height="30" horizontalAlign="center">
<mx:Button label="Data Set 1" click="changeData('set1')"/>
<mx:Button label="Data Set 2" click="changeData('set2')"/>
</mx:HBox>
Now we’ll need to make the function to switch between data sources. We’ve already laid the groundworks for this with the button we just created. On the click event the target XML data set is passed to a function called changeData. We’ll build that now below the xmlHandler function within the script tag.
private function changeData(dataSet:String):void{
//Determine which set should be loaded
switch (dataSet){
case ('set1'):
//Set URL target to Test Data 1
testData.url ="assets/test-data.xml";
break;
case ('set2'):
//Set URL target to Test Data 2
testData.url ="assets/test-data2.xml";
break;
default:
//If somehow it's neither, just leave it be
break;
}
//Send out new URL Request to refresh chart
testData.send();
}
The above code is a simple actionscript switch statement which evalutates the value of the passed string and then assigns the location of the corresponding test data XML to the url attribute of our HTTPService. Once it is assign, we have to send the request via the send method in order to retrieve the new data.
The nice part about data binding is that we do not need to make any additional changes to the chart structure. The chart is set to automatically display whatever the current value of testInfo is. With the above function, we are simply loading different data into testInfo, and Flex will take it from there. Go ahead and try it out now. If everything is working as planned you should see the chart change when a button is clicked. It looks good now, but we’re going to make one last change to really accent the chart changes.
Step 5 – Animate the Transition
Flex charts are smart when it comes to animations. We’re going to use on of the simplest ones to animate chart data transitions. Above the HTTPService tag, add the tag below.
<mx:SeriesInterpolate id="changeEffect" duration="2000"/>
This will make a nice transition between data. We give it an id in order to reference it from other locations, and then a duration of 2 seconds. To call this animation, add a showDataEffect attribute to the ColumnSeries tag and bind it to the SeriesInterpolate. This will call the transition effect every time new data is shown on the graph.
<mx:ColumnSeries showDataEffect="{changeEffect}" xField="name" yField="sat" displayName="Sat Score"/>
Step 6 – Graph Away
Go ahead and save what you’ve done and preview the results. If everything is in order you should have something looking like the screen below that transitions between data when the buttons are pressed. Not bad!

If something went wrong along the way I’ve included the source files to patch it up below. Be sure to experiment with the other chart types! Now you’ve added one more thing to your Flex arsenal. Congratulations!
Download the source files.
View the live demo.


