Flex Chart 中用dataFunction对数据进行处理

Python中文社区 2014-11-24

在flex中用chart对数据展示时,有时候数据中有空值,但是希望数据为空时能用其他默认值来代替,这个时候就可以用dataFunction来做对数据显示前的一个预处理。

<s:Application 
	xmlns:fx="http://ns.adobe.com/mxml/2009" 
	xmlns:mx="library://ns.adobe.com/flex/mx" 
	xmlns:s="library://ns.adobe.com/flex/spark" 
	height="600">
	<fx:Script><![CDATA[
		import mx.charts.CategoryAxis;
		import mx.charts.chartClasses.AxisBase;
		import mx.charts.chartClasses.Series;
		
		[Bindable] 
		public var SMITH:Array = [ 
		{month: 1, High:45.87,Low:null, open:25.19}, 
		{month: 2, High:45.74,Low:10.23, open:35.29}, 
		{month: 3, High:45.77,Low:12.13, open:45.19}, 
		{month: null, High:46.06,Low:10.45, open:15.59}, 
		]; 
		
		private function columnDataFunc(series:Series, item:Object, fieldName:String):Object { 
			if(fieldName == "yValue" && series.hasOwnProperty("yField"))
			{
				var yfield:String = series["yField"];
				if(item[yfield] == null)
				{
					return 123; 
				}
				//此时的返回值必须与数据类型相匹配。
				return item[yfield];
			}
			else if(fieldName == "xValue")
			{
				var xfield:String = categoryAxis.categoryField;
				//此时,必须返回为string类型的值,因为x轴为null时,chart控件会默认用此数据的index来代表,如果不为string的话,chart的图形会发生平移现象
				//但是记得此时必须和categoryDataFunction中的返回逻辑一样
				return item[xfield] != null ? item[xfield].toString() : "4";
			}
			else
			{
				return null;
			}
		} 
		private function categoryDataFunction(axis:AxisBase, item:Object):Object { 
			// 对数据源数据显示之前做处理,因为显示的时候都用string类型,所以可以返回任何类型
			return item.month == null ? "4" :  item.month; 
		} 
		
		protected function categoryAxisLabelFunction(item:Object, prevValue:Object, axis:CategoryAxis, categoryItem:Object):String
		{
			// labelFunction 仅仅决定显示的label的值
			var showString:String = item.toString() + " -label";
			return  showString;  
		}
		
	]]></fx:Script>
	<s:layout>
		<s:VerticalLayout/>
	</s:layout>
	<mx:ColumnChart id="chart" dataProvider="{SMITH}"
					showDataTips="true" width="100%" height="100%">
		<mx:horizontalAxis>
			<!-- The dataFunction replaces "categoryField='month'. -->
			<mx:CategoryAxis id="categoryAxis"  
							 dataFunction="categoryDataFunction"
							 labelFunction="categoryAxisLabelFunction"
							 categoryField="month"/>
		</mx:horizontalAxis>
		<mx:series>
			<!--
			The dataFunction replaces yField value, which cannot drill down
			into an object (close.High is not valid).
			-->
			<mx:ColumnSeries id="highClose" yField="High" maxColumnWidth="20" name="High"
							 dataFunction="columnDataFunc" />
			<mx:ColumnSeries id="lowClose" yField="Low" maxColumnWidth="20" name="Low"
							 dataFunction="columnDataFunc" />
		</mx:series>
	</mx:ColumnChart>
</s:Application>

相关推荐