Adobe Flex 3 Help

Using data labels

Data labels show static data on the chart control. They typically appear on the chart for each chart element (such as all pie wedges or all bars) for the entire time the chart is active. They are different from DataTip objects in that they typically show only the simple value of a chart element in a series (for example, a column's height or a pie wedge's percentage) and do not include other information such as the series name or complex formatting. DataTip controls are more interactive, since they appear and disappear as the user moves the mouse over chart elements. For more information about DataTip objects, see Using DataTip objects.

The following example shows a column chart with an active DataTip object and visible data labels:

A column chart with an active DataTip object and visible data labels.

A. DataTip B. Data label

The following chart series support data labels:

  • BarSeries
  • ColumnSeries
  • PieSeries

Just like DataTip controls, data labels are not enabled by default. You can add data labels by setting the value of the series' labelPosition property to inside or outside (for BarSeries and ColumnSeries) or inside, outside, callout, or insideWithCallout (for PieSeries). For more information, see Adding data labels. The default value of the series's labelPosition property is none.

The following example enables data labels on the columns by setting the value of the labelPosition style property to inside. You can click the button to change the position of the labels to outside.

<?xml version="1.0"?>
<!-- charts/BasicDataLabel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="setStartLabelLocation()">
  <mx:Script><![CDATA[
    import mx.collections.ArrayCollection;
  
    [Bindable]
     public var expenses:ArrayCollection = new ArrayCollection([
        {Month:"Jan", Income:2000, Expenses:1500},
        {Month:"Feb", Income:1000, Expenses:200},
        {Month:"Mar", Income:1500, Expenses:500}
     ]);
     
     private function setStartLabelLocation():void {
        cs1.setStyle("labelPosition", "inside");
        cs2.setStyle("labelPosition", "inside");
     }
     
     private function changeLabelLocation():void {
        var pos:String = cs1.getStyle("labelPosition");
        if (pos == "inside") {
            pos = "outside";
        } else {
            pos = "inside";
        }   
        cs1.setStyle("labelPosition", pos);
        cs2.setStyle("labelPosition", pos);
     }
     
  ]]></mx:Script>
  
  <mx:Panel title="Column Chart">
     <mx:ColumnChart id="myChart" 
        dataProvider="{expenses}" 
        showDataTips="true"
     >
        <mx:horizontalAxis>
           <mx:CategoryAxis 
                dataProvider="{expenses}" 
                categoryField="Month"
           />
        </mx:horizontalAxis>
        
        <mx:verticalAxis>
            <mx:LinearAxis minimum="0" maximum="2500"/>
        </mx:verticalAxis>
        
        <mx:series>
           <mx:ColumnSeries 
                id="cs1"
                xField="Month" 
                yField="Income" 
                displayName="Income"
           />
           <mx:ColumnSeries 
                id="cs2"
                xField="Month" 
                yField="Expenses" 
                displayName="Expenses"
           />
        </mx:series>
     </mx:ColumnChart>
     <mx:Legend dataProvider="{myChart}"/>          
  </mx:Panel>

  <mx:Button id="b1" 
    label="Change Label Location" 
    click="changeLabelLocation()"
  />

</mx:Application>

The executing SWF file for the previous example is shown below:

Adding data labels

By default, BarSeries, ColumnSeries, and PieSeries objects do not display data labels. To enable data labels on BarSeries and ColumnSeries objects, set the value of the labelPosition property to inside or outside. To enabled data labels on PieSeries, set the value of the labelPosition property to inside, outside, callout, or insideWithCallout.

The default value of the labelPosition property is none.

Because labelPosition property is a style property, you can set it either inline in the series' tag or by using the setStyle() method, as the following example shows:

mySeries.setStyle("labelPosition", "outside");

The contents of the data label are determined by several factors, in order of precedence:

  • labelField--Specifies a field in the data provider that sets the contents of the data label. This overrides any method specified by the labelFunction property.
  • labelFunction--Specifies a method that takes several arguments and returns a String that the chart series uses for the data label's contents. For more information, see Customizing data label values.
  • Default--If neither the labelField nor the labelFunction are specified, the default content of the data label is the value that the series uses to draw the chart element. This is the xField value for a ColumnSeries and the yField value for a BarSeries. For a PieSeries, the default content of the data labels is the value of the field property.

Setting the labelPosition property to inside restricts the amount of styling you can perform on the data labels. If the data labels are inside the chart elements (for example, inside the column in a ColumnSeries), their size is restricted by the available space within that element. A data label cannot be bigger than the chart element that contains it. If you try to set a data label to be larger than its underlying chart element, Flex scales and possibly truncates the contents of the data label. As a result, you should usually set the value of the labelPosition property to outside. For information about styling your data labels, see Styling data labels.

For 100%, stacked, and overlaid charts, the values of the series's labelPosition property can only be inside. If you set the labelPosition property to outside for these types of bar and column series, the value is ignored and the labels are rendered as if the labelPosition was inside.

If you set the labelPosition property to inside, you cannot rotate data labels.

Styling data labels

You can style the data labels so that their appearance fits into the style of your application. You can apply the following styles to data labels:

  • fontFamily
  • fontSize
  • fontStyle
  • fontWeight
  • labelAlign (when labelPosition is inside only)
  • labelPosition
  • labelSizeLimit

You can apply these styles by using type or class selectors in CSS or by using the setStyle() method. You can also set these properties inline in the series's MXML tag.

The following example shows how to use CSS class selectors to set the labelPosition and other properties that affect the appearance of data labels in a chart:

<?xml version="1.0"?>
<!-- charts/StylingDataLabels.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script><![CDATA[
    import mx.collections.ArrayCollection;
  
    [Bindable]
     public var expenses:ArrayCollection = new ArrayCollection([
        {Month:"Jan", Income:2000, Expenses:1500},
        {Month:"Feb", Income:1000, Expenses:200},
        {Month:"Mar", Income:1500, Expenses:500}
     ]);

    /*
    Style properties on series that affect data labels:
        fontFamily; fontSize; fontStyle; fontWeight;
        labelPosition; labelRotation; labelSizeLimit
    */     
  ]]></mx:Script>
  
  <mx:Style>
    .incomeSeries {
        fontSize:9;
        fontWeight:bold;
        labelPosition:inside;
        labelAlign:top;
    }

    .expensesSeries {
        fontSize:8;
        labelPosition:inside;
        labelAlign:middle;
    }

  </mx:Style>  
  
  <mx:Panel title="Column Chart">
     <mx:ColumnChart id="myChart" 
        dataProvider="{expenses}" 
        showDataTips="true"
     >
        <mx:horizontalAxis>
           <mx:CategoryAxis 
                dataProvider="{expenses}" 
                categoryField="Month"
           />
        </mx:horizontalAxis>
        
        <mx:verticalAxis>
            <mx:LinearAxis minimum="0" maximum="2500"/>
        </mx:verticalAxis>
        
        <mx:series>
           <mx:ColumnSeries 
                xField="Month" 
                yField="Income" 
                displayName="Income"
                styleName="incomeSeries"                
           />
           <mx:ColumnSeries 
                xField="Month" 
                yField="Expenses" 
                displayName="Expenses"
                styleName="expensesSeries"
           />
        </mx:series>
     </mx:ColumnChart>
     <mx:Legend dataProvider="{myChart}"/>          
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

Labels are scaled and possibly truncated if they are too big for the area. Labels will never overlap each other or other chart elements.

For PieSeries objects, you can also specify the gap and stroke of callout lines that associate a data label with a particular wedge in the pie. For more information, see Using data labels with PieChart controls.

Aligning data labels

You can align data labels so that they are positioned, either vertically or horizontally, relative to the underlying chart element. For example, you can center a data label over a column in a ColumnChart control, or align it to the left of all bars in a BarChart control.

To align data labels, you use the series' labelAlign style property. For ColumnSeries objects, valid values are middle, top, and bottom. For BarSeries objects, valid values are left, center, and right. The defaults are middle and center, respectively.

You can only set the labelAlign style if the labelPosition property is set to inside. Label alignment is ignored if the labelPosition is outside.

You cannot change the alignment of data labels on a PieSeries object.

ColumnChart controls have two additional properties that you can use to control the way data labels are rendered: showLabelVertically and extendLabelToEnd. These properties are important when the available space for labels is not sufficient to render the entire label. If you set showLabelVertically to true, Flex can render the label vertically rather than horizontally if the columns are not wide enough to render them normally. If you set extendLabelToEnd to true, then Flex can use the space between the data item's edge and the outer boundary of the chart to render the label in, rather than truncate the label at the end of the data item's column.

Customizing data label values

You can customize the value of your data labels. For example, you can prepend a dollar sign ($) or apply numeric formatters to the data labels to make your chart more readable. You can change the value of the data label altogther if you want.

To customize the contents of a data label, you use the labelFunction property of the series to specify a callback function. The function specified in labelFunction returns a String that Flex displays as the data label. Flex calls this callback function for each chart element in the series when the data labels are first rendered, and calls this method any time the labels are rendered again (for example, if the data changes).

The exact signature of the custom label callback function depends on the series that you are using it with. For BarSeries and ColumnSeries objects, the function takes two arguments (see Customizing data labels for ColumnSeries and BarSeries objects); for PieSeries objects, the function takes four arguments (see Customizing data labels for PieSeries objects).

Customizing data labels for ColumnSeries and BarSeries objects

For a ColumnSeries or BarSeries object, the signature for the custom label callback function is:

function_name(element:ChartItem, series:Series):String { ... }

The following table describes the parameters of the labelFunction callback function for a ColumnSeries or BarSeries object:

Parameter

Description

element

A reference to the ChartItem that this data label applies to. The ChartItem represents a single data point in a series.

series

A reference to the series that this data label is used on.

When you customize the value of the data label, you typically get a reference to the series item. You do this by casting the element argument to a specific chart item type (BarSeriesItem or ColumnSeriesItem). You then point to either the yNumber or xNumber property to get the underlying data.

You can also get a reference to the current series by casting the series argument to the specific series type (ColumnSeries or BarSeries). This lets you access properties such as the yField or xField.

The following example creates data labels for each of the columns in the ColumnChart control:

<?xml version="1.0"?>
<!-- charts/DataLabelFunctionColumn.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script><![CDATA[
  
    import mx.charts.ChartItem;
    import mx.charts.chartClasses.Series;
    import mx.charts.series.items.ColumnSeriesItem;
    import mx.collections.ArrayCollection;
  
    [Bindable]
     public var expenses:ArrayCollection = new ArrayCollection([
        {Month:"Jan", Income:2000, Expenses:1500},
        {Month:"Feb", Income:1000, Expenses:200},
        {Month:"Mar", Income:1500, Expenses:500}
     ]);
     
     private function setCustomLabel(element:ChartItem, series:Series):String {
        // Get a refereence to the current data element.
        var data:ColumnSeriesItem = ColumnSeriesItem(element);        
        
        // Get a reference to the current series.        
        var currentSeries:ColumnSeries = ColumnSeries(series);

        // Create a return String and format the number.
        return currentSeries.yField + ":" + " $" + nf1.format(data.yNumber);        
     }
     
  ]]></mx:Script>
  
  <mx:NumberFormatter id="nf1" useThousandsSeparator="true"/>
  
  <mx:Panel title="Column Chart">
     <mx:ColumnChart id="myChart" 
        dataProvider="{expenses}" 
        showDataTips="true"
     >
        <mx:horizontalAxis>
           <mx:CategoryAxis 
                dataProvider="{expenses}" 
                categoryField="Month"
           />
        </mx:horizontalAxis>
        
        <mx:verticalAxis>
            <mx:LinearAxis minimum="0" maximum="3000"/>
        </mx:verticalAxis>
        
        <mx:series>
           <mx:ColumnSeries 
                labelPosition="outside"
                xField="Month" 
                yField="Income" 
                displayName="Income"
                labelFunction="setCustomLabel"
           />
           <mx:ColumnSeries 
                labelPosition="outside"
                xField="Month" 
                yField="Expenses" 
                displayName="Expenses"
                labelFunction="setCustomLabel"
           />
        </mx:series>
     </mx:ColumnChart>
     <mx:Legend dataProvider="{myChart}"/>          
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

You can also access the specific field in the data provider that provides the data. For example, in the previous example, you could get the value of the data item (in this case, the value of the Income field) by using code similar to the following:

var item:ColumnSeriesItem = ColumnSeriesItem(element);
var s:String = item.item.Income;
return s;

This is not a recommended practice, however, because it makes the callback function less reusable and can force you to use additional code to detect which column you are providing data labels for.

Customizing data labels for PieSeries objects

For a PieSeries object, the signature for the custom label callback function is:

function_name(data:Object, field:String, index:Number, percentValue:Number):String { ... }

The following table describes the parameters of the labelFunction callback function for a PieSeries:

Parameter

Description

data

A reference to the data point that chart element represents; type Object.

field

The field name from the data provider; type String.

index

The number of the data point in the data provider; type Number.

percentValue

The size of the pie wedge relative to the pie; type Number. If the pie wedge is a quarter of the size of the pie, this value is 25.

The following example generates data labels for a PieSeries object that include data and formatting. It defines the display() method as the labelFunction callback function to handle formatting of the label text.

<?xml version="1.0"?>
<!-- charts/PieLabelFunction.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script><![CDATA[
     import mx.formatters.*;
     import mx.collections.ArrayCollection;
     [Bindable]
     public var expenses:ArrayCollection = new ArrayCollection([
        {Expense:"Taxes", Amount:1900000},
        {Expense:"Salaries", Amount:1350000},
        {Expense:"Building Rent", Amount:300000},
        {Expense:"Insurance", Amount:750000},
        {Expense:"Benefits", Amount:800000},
        {Expense:"Miscellaneous", Amount:900000}
     ]);
     public function display(
        data:Object,
        field:String,
        index:Number,
        percentValue:Number):String
     {
            return data.Expense + "\n$" + data.Amount +
            "\n" + round(percentValue,2) + "%";
     }
     // Rounds to 2 places:
     public function round(num:Number, precision:Number):Number {
        var result:String;
        var f:NumberFormatter = new NumberFormatter();
        f.precision = precision;
        result = f.format(num);
        return Number(result);
     }
  ]]></mx:Script>
  <mx:Panel title="Expenditures for FY04">
     <mx:PieChart id="chart" 
        dataProvider="{expenses}" 
        showDataTips="false"
     >
        <mx:series>
           <mx:PieSeries
                labelPosition="callout"
                field="Amount"
                labelFunction="display"
                nameField="Expense"
           />
        </mx:series>
     </mx:PieChart>
     <mx:Legend dataProvider="{chart}"/>          
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below: