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.














Discussion
January 12th, 2009 at 7:48 AM
Is wonderful tutorial about charts. It was interesting to see and experiment. I know actionscript but I am new to Flex, learing on my-own. thanks for the help.
January 17th, 2009 at 6:04 PM
Great tutorial. Say you want to have two seprate charts with this data transition effect do you create 4 sets (two more for the additional chart)?
February 4th, 2009 at 10:28 AM
Just what I was looking for. Thank you!
March 11th, 2009 at 4:10 PM
Great tutorial. Just what I was looking for. Thanks a lot!
March 27th, 2009 at 5:55 AM
Nicely done Zach, I’ve added the link to Flashtuts+
Ian Yates’s last blog post..Build an Efficient Flash DecalSheet System
April 2nd, 2009 at 4:51 PM
For some strange reason, I do not see the graphs, even when using the source files…
April 2nd, 2009 at 5:03 PM
I take that back! (nothing like a restart)
Thank you! Great tutorial!
May 16th, 2009 at 7:13 PM
Great tutorial. Thank you!
May 19th, 2009 at 10:56 AM
I tried this and it worked perfectly in a small application, however when i tried to do it on a ‘State’ within an application i got a parsing error for the httpservice. Should this still work when it’s creating a chart on state or should i be using something else?
May 19th, 2009 at 8:43 PM
@Gussy
Without much background on your application, I can’t say one way or another. I haven’t done much in depth with charts and states, but I would think you should be able to. The only thing I would recommend is to just load the contents of the XML in when the application loads. This may help when fix things when the state is actually loaded.
Let me know how things go, I’m curious myself.
June 1st, 2009 at 1:31 PM
hi zach
you used sql2005 with flex 3
June 13th, 2009 at 9:42 AM
Great tutorial.. Thanks a bunch!
July 17th, 2009 at 10:05 AM
ITS REAlly GOOOD FOR BEGINNERS ..
September 19th, 2009 at 5:37 PM
Excellent resources that you offer, thanks so much!
How would I use similar buttons to switch between two variables within the same xml file?
Example: Toggling between John, Joe, and Elyse’s SAT and PSAT scores.
September 29th, 2009 at 2:53 PM
Great tutorial,
Is it possible to add the $ sign to the left column as well as to the Datatips???
Thanks!
October 10th, 2009 at 3:07 PM
Hello… this seems like it will do what I want it to do but…
1) I created a new project as indicated in the instructions. 2) Downloaded the XML data files and placed them in an assets folder.
3) Followed the instructions to the ‘t’. And I get the following error when I run the app in BOTH Firefox and IE.
– ERROR –
[RPC Fault faultString="HTTP request error" faultCode="Server.Error.Request" faultDetail="Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: assets/test-data.xml"]. URL: assets/test-data.xml”]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:216]
at mx.rpc::Responder/fault()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\Responder.as:49]
at mx.rpc::AsyncRequest/fault()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:103]
at DirectHTTPMessageResponder/errorHandler()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\messaging\channels\DirectHTTPChannel.as:343]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/redirectEvent()
– END ERROR –
4) I got the same error when I downloaded and copied the existing MXML source from this site.
Can you tell me if I’ve done something wrong. Not sure what I would have done… It seems pretty straight forward.
Thanks.
October 10th, 2009 at 4:32 PM
@Damian
Flex (and Flash) are unable to load external files on local machines due to permission and security issues. If you’re testing locally, I recommend you move to a testing server.
October 10th, 2009 at 7:04 PM
Zach,
Thanks for the reply. I was testing the source locally. I moved the release files to the “development” server (not locally) and the files were loaded and now works great.
So I’ll have to mess around with fixing the permissions in Vista, so that I’m able to do the development testing locally.
Thanks again!
October 30th, 2009 at 2:06 PM
I’d like to offer you testing another flex charting components made by amCharts: http://flex.amcharts.com
.-= Antanas´s last blog ..amCharts introduces Flex components =-.
November 6th, 2009 at 6:38 AM
Wow, what a great tutorial! wish i had found it earlier )) we recently purchased flex chart component for our system from http://www.flexmonster.com and are very satisfied so far
.-= A.Kvederis´s last blog ..COMINDWORK/TAG: Processes [Alex Postnikov edited] =-.
Join the Conversation!
Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.