Saturday, May 30, 2009

Flex: Showing data in the legend of a Pie Chart

By default the legend class does not allow to output actual data values. All it can show is the marker's label and color.
After searching the web, strangely enough, I did not find any published solution, and decided to extend the legend class in my application.
Today, I am sharing my work with you.

For the illustration I took an example from the official documentation of PieChart class. The name of the main application is TestLegend.mxml. All you need to do here is to add 'legendItemClass' property to the Legend tag. The Legend tag will look like:

<mx:Legend dataProvider="{chart}" legendItemClass="utilities.CustomPieLegendItem"/>

Next step is to create CustomPieLegendItem class, which extends LegendItem. I created a 'utilities' folder and added a new class there, in

package utilities
import mx.charts.LegendItem;
import mx.charts.series.PieSeries;
import mx.collections.ArrayCollection;

public class CustomPieLegendItem extends LegendItem

public function CustomPieLegendItem()

protected override function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {

var data:ArrayCollection = (element as PieSeries).dataProvider as ArrayCollection;
var dataNum:int = data.length;

for (var i:int=0; i<dataNum; i++) {
if (data[i].Country == this.label) {
// uncomment this line if you want to show all three data: Gold, Silver and Bronze
//this.label += " (" + data[i].Gold + "/" + data[i].Silver + "/" + data[i].Bronze + ")";
this.label += " (" + data[i].Gold + ")";

super.updateDisplayList(unscaledWidth, unscaledHeight);


And voila!

I think this solution is pretty self explanatory. If not, don't hesitate to ask a question. :)

Working example you can see here.
Source code is available here.

I hope it helped you to save some time inventing the solution how to show the data in legend of the chart.