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.

New MXML Application

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.

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.

We send this HTTP request using the creationComplete event in the application tag.

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.

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.

It looks complicated, but let’s break it down to the basics:

  1. The VBox is used to contain and center the components it contains. It only serves as a design aide.
  2. The Panel is  used to contain the chart and display a title. It only also only a design aide.
  3. 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.

  4. The horizontalAxis controls the information displayed along the x-axis. The CategoryAxis specifies the data source and field from data source to load from.
  5. The series tag contains the information that will be charted.
  6. 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.
  7. 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.

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.

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.

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.

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!

Finished SAT Chart

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.

Posted Saturday, December 27th, 2008 · Back to Top

SPONSOR

Add Comment

36 Comments 12 Mentions

  1. Satish Author Editor

    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.

    ·

  2. john Author Editor

    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)?

    ·

  3. Tim Scollick Author Editor

    Just what I was looking for. Thank you!

    ·

  4. Vladimir Author Editor

    Great tutorial. Just what I was looking for. Thanks a lot!

    ·

  5. Ian Yates Author Editor

    Nicely done Zach, I’ve added the link to Flashtuts+ ;-)

    Ian Yates’s last blog post..Build an Efficient Flash DecalSheet System

    ·

  6. Chris Bond Author Editor

    For some strange reason, I do not see the graphs, even when using the source files…

    ·

  7. Chris Bond Author Editor

    I take that back! (nothing like a restart)

    Thank you! Great tutorial!

    ·

  8. Jose Zerpa Author Editor

    Great tutorial. Thank you!

    ·

  9. Gussy Author Editor

    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?

    ·

    • Zach Dunn Author Editor

      @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.

      ·

  10. Jose Davila Author Editor

    hi zach

    you used sql2005 with flex 3

    ·

  11. DB Author Editor

    Great tutorial.. Thanks a bunch!

    ·

  12. Madyyyyyy Author Editor

    ITS REAlly GOOOD FOR BEGINNERS ..

    ·

  13. Alex Author Editor

    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.

    ·

  14. Jess Author Editor

    Great tutorial,
    Is it possible to add the $ sign to the left column as well as to the Datatips???

    Thanks!

    ·

  15. Damian Author Editor

    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.

    ·

    • Zach Dunn Author Editor

      @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.

      ·

  16. Damian Author Editor

    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!

    ·

  17. Antanas Author Editor

    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 =-.

    ·

  18. A.Kvederis Author Editor

    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] =-.

    ·

  19. jsre Author Editor

    Very nice tutorial for the beginners. great use of comments about the codes.kudos to the author.jsre.

    How can i include another column in “Y” axis to show some other values to compare.

    Thanks in advance

    ·

  20. Vinod Author Editor

    hey Nice tutorials for the beginners…:) Thanks a lot.

    ·

  21. Abhishek Author Editor

    Hi , its working on the same machine when the page is opened as local host.
    However when from anyother machine I try to access it using http://ip/…./bin-debug/charts.html Only the panel / legends/buttons are coming and the actual BAR is missing .
    tried from several machines but in vain …

    ·

  22. Shymoon Author Editor

    Thank u sooooo much.

    ·

  23. P28 Author Editor

    Can you please give some more examples related to graph?

    ·

  24. afjal Author Editor

    how can i read local xml file in flex mobile project

    ·

  25. Katrien Author Editor

    For some reason I cannot POST a value using HTTPService in Flex to my php file.
    If I hardcode the value in the php it works 100%, using just the HTTPService with GET.
    I need the xml result as dataProvider for a Flex graph and like I said, it works 100% and the graph displays correctly with a hardcoded value in the php.
    If I test in the browser like so:
    http://localhost/……..my_url/myfile.php?itemID=1 I get an undefined index error and obviously if I run my Flex application I get no graph.
    If I change the $_POST to $_GET in php and just test in browser I get the correct output.

    Please help!

    Here’s the php:
    <?php header("Content-Type:text/xml");
    echo '’;
    //connection info
    define(“DATABASE_SERVER”, “localhost”);
    define(“DATABASE_USERNAME”, “root”);
    define(“DATABASE_PASSWORD”, “”);
    define(“DATABASE_NAME”, “xx”);

    $dbc = mysqli_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);

    $itemID=$_POST['itemID'];

    $q = “SELECT ID, Name FROM inventory where AreaID = $itemID”;
    $i=0;
    $r = mysqli_query($dbc,$q);

    while ($row=mysqli_fetch_array($r, MYSQLI_ASSOC)){
    $i++;
    echo ”
    {$row["Designation"]}
    {$i}

    “;
    }
    echo ”;
    ?>

    Here’s the Flex:

    {1}

    [Bindable]
    private var testInfo:XMLList;

    private function xmlHandler(event:ResultEvent):void
    {
    testInfo = event.result.node;
    testChart.dataProvider=testInfo;
    }

    protected function getChartData_resultHandler(event:ResultEvent):void
    {
    testData.send();
    }

    ·

  26. Katrien Author Editor

    Sorry, some of the Flex didn’t appear. Here it is:

    {1}

    ·

  27. Katrien Author Editor

    Can’t manage to get the code to display correctly.
    The gist of it is: everything works fine; xml outputs correctly. Just can’t POST the value…

    ·

  28. Katrien Author Editor

    Solved. Problem was I never called/invoked the POST HTTPService in my Flex application. However, I’ve since dropped the POST HTTPService altogether. I’m only using a GET HTTPService with <s:Request where I send the itemID to the server. In my php I use $_REQUEST, but I know I can also use $_GET.

    ·

  29. Tom Author Editor

    Great tutorial! Thanks!

    ·

  30. Olav Nes Author Editor

    Maybe you could do a follow-up on how to customize these charts as well.

    Olav

    ·

  31. crestwood preschool Author Editor

    Its very nice article and i appreciate you for such nice info.

    ·

  32. hasitha Author Editor

    this is great tutorial,thank u very much for sharing your knowledge with us

    ·

  33. chart dude Author Editor

    thanks, that’s very clear and easy to follow.
    readers may also be interested in reading up on the FusionCharts for Flex extension http://www.fusioncharts.com/extensions/adobe-flex

    ·

  34. Gagandeep Singh Author Editor

    I am not able to animate the graph.

    My chart code is like this.

    What am I doing wrong.

    ·

 

Build Internet by One Mighty Roar. Since 2008.