Communicating Charts with Flex

June 19th, 2007 by grant · 23 Comments

»Using Adobe Flex to create charts and graphs.

 

Getting started

Creating graphs with Adobe’s Flex 2 is a pretty simple task, just throw together some short XML and you’re done. But like most “easy” technologies things get a little more difficult when you want to do more advanced things like making sections of the graphs stand out or keeping multiple graphs in sync with one another. In this tutorial I will take you through how to give your graphs a little more “flash” and how to make things happen in one graph when you click on another graph.

If you haven’t already you can download the free Flex 2 SDK from Adobe. And you can download a free trial of the Flex 2 charting library.

In your favorite text editor (Eclipse anyone?) start a new file and start with some basic code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
  xmlns:local="*" xmlns:view="view.*">
 
<mx:Script>
  <![CDATA[
    import mx.collections.ArrayCollection;
 
    [Bindable]
    private var profitPeriods:ArrayCollection = new ArrayCollection( [
    { period: "Qtr1 2006", profit: 32 },
    { period: "Qtr2 2006", profit: 47 },
    { period: "Qtr3 2006", profit: 62 },
    { period: "Qtr4 2006", profit: 35 },
    { period: "Qtr1 2007", profit: 25 },
    { period: "Qtr2 2007", profit: 55 } ]);
  ]]>
</mx:Script>
 
  <mx:Panel x="10" y="10" width="100%" height="100%" title="Profit By Period">
 
    <mx:PieChart id="profitPie" dataProvider="{profitPeriods}" showDataTips="true" width="100%" height="100%">
      <mx:series>
        <mx:PieSeries field="profit" nameField="period" labelPosition="callout" showDataEffect="{interpolate}" />
      </mx:series>
    </mx:PieChart>
  </mx:Panel>
</mx:Application>

Getting more advanced

This code basically creates a sample dataset and a pie chart to display it. Nothing fancy and if we were using an XML feed we wouldn’t have any need for ActionScript at all, since we are only using it to create the data in this example.

Now let’s say that your customer (or boss) wants to have the data shown in multiple ways. For our example let’s say that he wants to see a pie graph, a bar graph and a data grid. So he can see the data in whatever way he wants to. No problem there, throwing another chart and grid on the page is just a few more lines of xml, but what if they are to interact? Say your boss wants to be able to click on a piece of the pie chart and have the same record highlighted in the pie chart, the column chart and the data grid. Now we’re going to have to whip out the ActionScript.

We are going to need three methods, one to highlight the pie graph, one for the column chart and a final one for the data grid. Then we can call all three of these methods whenever a chart or grid is clicked on. We are using three methods instead of just one giant method in case we ever want to use them again, in a different circumstance.

import flash.display.DisplayObject;  //The items in the column chart are DisplayObjects
 
private var prevSelectedColumn:DisplayObject;
/*
We want to be able to "unhighlight" whatever column we highlighted last time, so
we'll create a variable to keep it simple. If you are using a graph with
multiple datasets then you'll obviously want to loop through them and reset them
that way instead of using this method.
*/
 
/*
* This function will highlight a column/bar in a column/bar chart
* @param barName  The name/id of the bar/column chart
* @param barIndex The position of the column you want to highlight
*/
private function barHighlight( barName:String, barIndex:int ):void
{
  if (prevSelectedColumn)  //If we selected something before, unselect it:
  {
    prevSelectedColumn.alpha = .8;
    prevSelectedColumn.filters = [];  //remove the filters
  }
 
  //This gets the individual column that we are looking for
  prevSelectedColumn = this[barName].series[0].getChildAt( barIndex );
 
  if (prevSelectedColumn)  //highlight the new column:
  {
    prevSelectedColumn.alpha = 1;
    prevSelectedColumn.filters = [new GlowFilter(), new DropShadowFilter()];
  }
}
 
/*
* This function will highlight a row in a data grid
* @param dataGridName The name of the data grid that contains the row to highlight
* @param rowIndex   The position of the row in the grid to highlight
*/
private function rowHighlight( dataGridName:String, rowIndex:int ): void
{
  this[dataGridName].selectedIndex = rowIndex;  //the easy one...
}
 
/*
* This function "explodes" a piece of pie from a pie chart
* @param pieName  The name of the pie chart that is to be modified
* @param pieIndex The index of the pie piece that is to be modified
*/
private function pieHighlight( pieName:String, pieIndex:int ):void
{
  var explodeData:Array = [];  //create an empty array
  explodeData[ pieIndex ] = 0.15; //Set the index of our pie piece to > 0
  this[pieName].series[0].perWedgeExplodeRadius = explodeData;
  /*
  The pie's wedges can be "exploded" outward to highlight them. The amount is
  controlled by an array, so we just create a empty array (which would set
  everything to no padding) and add padding for the index that is to be
  highlighted. This has the added bonus of un-highlighting the piece that was last
  highlighted (if any). Sweet!
  */
}

Adding events

Of course, this is using inline ActionScript. If you want to separate it into another file you’ll have to use “Application.application” instead of “this” (see the downloadable GraphHighlighting.as file below). That should give us a snazzy little effect every time we click on an item in any of the charts or in the grid. But they won’t be doing any effects unless we add event handlers to our objects. Let’s do that now.

So change the xml for your pie chart and add this to the PieChart tag:

itemClick="pieChartClick(event, 'profitGrid', 'profitBar');"

And then you can add the ActionScript to handle that event (which, of course, will call our handy three functions):

/*
* This is run when the pie chart is clicked on
* @param event    The click event
* @param dataGridName The string name of the data grid that should be highlighted
* @param barName  The string name of the column chart that should be highlighted
*/
private function pieChartClick( event:ChartItemEvent, dataGridName:String, barName:String ):void
{
  pieHighlight( event.currentTarget.id , event.hitData.chartItem.index );
  rowHighlight( dataGridName, event.hitData.chartItem.index);
  barHighlight( barName, event.hitData.chartItem.index );
}

Then do this for the other chart and the datagrid and you’ll be set.

Conclusion and downloads

So, if you did your calculations correctly, remembered to carry the one and crossed your fingers you probably ended up with something like this:

Actually, it probably won’t look like that, but the sample code download does (see below).

It is more likely that you’ll probably be making the charts communicate using different data (click on one part of a chart and get detailed information in another chart), but this should at least get you started in the right direction.

Download the complete inline ActionScript example: This file is the complete example and you should be able to save it and compile it with the mxml compiler that came with the Flex 2 SDK (assuming you have the charting library, or the charting trial library).

Download the “external” ActionScript methods: This file is what you can use if you want to keep these functions in your library for future use. I put this in the FlexAS.GraphHighlighting package, so if you don’t change the package name you should put this into a “FlexAS/GraphHighlighting/” subfolder off of your main flex directory.

Tags: Flex · Free · Programming · Software · Web design · XML

 

23 responses so far ↓

  • 1 kayrules // Sep 27, 2007 at 1:46 am

    just what i need.. Thank you

  • 2 SomeGuy // Oct 10, 2007 at 3:21 pm

    When you click a slice of the pie, the labels disappear from the pie graph. Is there any way I can make this not happen? Thanks.

  • 3 Grant // Oct 10, 2007 at 10:17 pm

    SomeGuy: Not without rewriting a bunch of backend stuff and creating your own animation. The bad part about Flex is that it is only easy to do simple things…once you start getting complex you run into walls.

  • 4 CodeRambler // Nov 13, 2007 at 6:57 am

    This is great. Just one question, when I click on the pie/Barchart, I’d like to display a breakdown of information in the grid. Can you give me a clue? Thanks.

  • 5 coderambler // Nov 13, 2007 at 7:08 am

    This is brilliant, and I’ve learnt such a lot from it. Say I want to breakdown the profit, and show details for the clicked-on quarter in the grid, can you give me a clue? Thanks.

  • 6 coderambler // Nov 13, 2007 at 7:49 am

    Hi, this is brilliant, and has helped me enormously. Extending your example, I have the transactions which make up the profit as part of an xml file. How can I populate the grid with these once I click on a wedge? Many thanks!

  • 7 Silypuddy // Nov 21, 2007 at 3:03 pm

    I can’t seem to find the effect that makes the pie chart explode and implode “slowly”. What effect is it. All my pie charts just jump to the explode radius vs. doing it “slowly”. Other than that, thanks for a great example!

  • 8 Peter // Nov 25, 2007 at 3:18 am

    Silypuddy,

    Search through the code for the following line, it should control the timing of the animation. You can add a “duration” property to set an explicit animation duration (in milliseconds).

  • 9 fishball // Feb 11, 2008 at 5:43 am

    hey thanks for this! but is there anyway i can get off the “flex charting trial” watermark off?

  • 10 Grant // Feb 12, 2008 at 10:03 am

    To remove the watermark you need to purchase a Flex Charting license from Adobe. If your project isn’t in any hurry I would suggest waiting for Flex 3 to be released in a month or two.

  • 11 Benjie // Feb 27, 2008 at 10:28 am

    Thanks for this, very useful.

    You can write less code by passing the datagrid/piecharts in as actual objects rather than their names as strings. So you would end up writing just “datagrid.SelectedIndex” rather than “Application.application.[datagridname].SelectedIndex” :o )

  • 12 financetech // Mar 6, 2008 at 11:55 am

    Has anyone looked at YUI?

    http://developer.yahoo.com/yui

    It has a charting library based on flex, but it also has integration with the rest of page elements, events, and web services.

  • 13 raghavendras // Jun 27, 2008 at 11:29 pm

    Hi,

    I have seen this examples its very beautiful but i wanted this data should be pulled from mysql using php and outputting in xml can we do that….if you have any example can you forward to me please….

  • 14 Grant // Jun 30, 2008 at 5:51 pm

    @raghavendras

    Within PHP you just need to be able to build an XML file from your data and have Flex grab that file using it’s internal data processing methods.

  • 15 multiple Action Script tag // Jul 24, 2008 at 9:44 am

    Hi
    Can we add multiple Actionscript tag in the mxml file for example

    I am getting the error in that.

    Please help me ASAP
    Thanks and Regards
    Monika

  • 16 Grant // Jul 25, 2008 at 10:52 pm

    Monika,

    Sorry, I didn’t get the example you tried to show. Try and post again so I can see what you are trying to do.

  • 17 manish // Jul 29, 2008 at 3:24 pm

    thanks it worked for me!!!!!!!!!

  • 18 Andi // Jan 12, 2009 at 12:52 pm

    Is there any way to show both the data and the field the data corresponds to in the series? I see even using an array and object will only show the data. Any help is ginormously appreciated!
    Thanks,
    Andi

  • 19 Pete // Mar 19, 2009 at 12:13 am

    Thank you for the helpful example.
    Is there a way to force datatips, e.g., have the piechart and barchart datatips popup simultaneously when clicking the corresponding index in the datagrid?

  • 20 Shweta // May 13, 2009 at 9:31 am

    This is very good article.
    I would like to know can we draw half pie chart only.
    We have requirement to show only 180 degree pie chart & do operation on that only.
    Please let me know is it possible?

  • 21 Mannjit // May 31, 2009 at 8:03 pm

    I need to create an editable XY chart from data. It should be interactive in a manner that I should be delete data points from the chart points. i.e. I should be ab;e to delete the oints from chart and corresponding data from table may get delete. Can any body help me to create a chart of this kind in flex.
    manjit

  • 22 Jimmy // Dec 2, 2009 at 7:10 pm

    The sample is very good and get a lot of people here.
    I had same question like draw half pie: Can we use mouse drag the wedges’ line to change it area.

    Thanks for help the code.

    Jimmy

  • 23 kanni // Dec 22, 2009 at 3:32 pm

    hi, can anyonw tell me how to draw a graph i.e how to point the axis and how you can retirieve values from the MySQl . and i read for every connection of databse with flex we need a backend lang support like java or php is tht true . if true can anyone show me the connection of mysql to the flex application. also tell m ewhere to write the java application if we need java code? thx in advance

Leave a Comment


+ 8 = twelve