1. Code
  2. Coding Fundamentals
  3. XML

Create a Dynamic Bar Graph Generator Using XML + AS3

Scroll to top
5 min read

A bar chart or bar graph is a chart with rectangular bars whose lengths are proportional to the values they represent. They're commonly used for comparing two or more values that were taken over time or under different conditions, usually on small data sets.

In this tutorial, we'll create a bar graph generator using XML and AS3.

Step 1: Brief Overview

Using ActionScript 3, we will get the necessary graph data from an XML file, then display the converted data into animated bars and an info area.

Step 2: Starting

Open Flash and create a new Flash File (ActionScript 3).

Set the stage size to 600x300 and add a gray radial background (#E6E6E6, #CCCCCC).

Our graph generator will be created entirely by code, so this will be the only thing you will do in the Stage.

Step 3: XML

Open yout favorite XML editor (any text editor will work) and add the following lines:

1
2
<?xml version="1.0"?>
3
	<graphs width="50">
4
		<graph name="Yellow" value="50" color="0xFDC13E"/>
5
		<graph name="Blue" value="80" color="0x25B7E2"/>
6
		<graph name="Green" value="30" color="0xB8CF36"/>
7
		<graph name="Red" value="10" color="0xE7473F"/>
8
	</graphs>

This is the XML that we'll use to get the data, we won't be using the childrens' names, but the attributes.

  • width: The width of each bar.
  • name: The name of the element, to be displayed in the info area.
  • value: The value of that element, displayed at the top of the bars.
  • color: The color of the bar, in Hexadecimal.

This is the file that the end user will need to edit to show their own data.

Step 4: ActionScript!

It's ActionScript time.

Create a new ActionScript File (Cmd + N) and save it as "Graph.as", in your classes directory.

Step 5: Package

1
package
2
{

The package keyword allows you to organize your code into groups that can be imported by other scripts. It's recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: myClasses.

In the example, the class is stored in the same location as the Fla file.

Step 6: Importing Necessary Classes

These are the required classes, for a more detailed description about every class, please refer to the Flash Help (F1).

1
2
import fl.transitions.Tween;
3
import fl.transitions.easing.Strong;
4
import flash.display.Sprite;
5
import flash.text.TextField;
6
import flash.text.TextFormat;
7
import flash.text.TextFieldAutoSize;
8
import flash.net.URLLoader;
9
import flash.net.URLRequest;
10
import flash.events.Event;

Step 7: Declaring and Extending the Class

The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.

1
2
public class Graph extends Sprite
3
{

In this example, the Graph class inherits all the methods and properties of the Sprite Class.

Step 8: Variables

These are the variables we will use, explained in the comments.

1
2
private var graphContainer:Sprite = new Sprite();
3
private var xmlFile:XML; //The XML Object to parse the XML file

4
private var urlLoader:URLLoader = new URLLoader(); //The file loader

5
private var totalBars:int; //Stores the number of bars of the graph

6
7
private var tween:Tween; //A Tween object for animation

8
private var tf:TextFormat = new TextFormat(); //TextFormat

Step 9: Constructor

The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object, or runs using the Document Class.

1
2
public function Graph():void
3
{
4
	/* Text Format */
5
6
	tf.color = 0x666666;
7
	tf.size = 12;
8
	tf.font = "Helvetica";
9
10
	createGraphContainer();
11
	loadXML();
12
	createBars();
13
}

Step 10: Graph Container

This function will create the x and y axis lines of the graph using the drawing API.

1
2
private function createGraphContainer():void
3
{
4
	graphContainer.graphics.lineStyle(1, 0x9C9C9E);
5
	graphContainer.graphics.moveTo(30, 30);
6
	graphContainer.graphics.lineTo(30, 270);
7
	graphContainer.graphics.lineTo(570, 270);
8
9
	addChild(graphContainer);
10
}

Step 11: Load XML Function

This is the function that handles the loading of the XML file. We specify a default paramenter to avoid calling the function using another .as file, instead we're going to call it from the Document Class.

1
2
private function loadXML(file:String = "graph.xml"):void //Your xml data file

3
{
4
	urlLoader.load(new URLRequest(file)); //Loads the file in the parameter

5
	urlLoader.addEventListener(Event.COMPLETE, parseXML); Calls a function when the load is complete
6
}

Step 12: Parse XML

This function sets the data loaded to the XML object and calls the functions to create the graph using that data.

1
2
private function parseXML(e:Event):void
3
{
4
	xmlFile = new XML(e.target.data);
5
	totalBars = xmlFile.children().length();
6
7
	createBars();
8
	displayNames();
9
}

Step 13: Create Bars

This code handles the bar creation.

1
2
private function createBars():void
3
{
4
	for (var i:int = 0; i < totalBars; i++)//This for checks the number of bars in the xml

5
	{
6
		var bar:Sprite = new Sprite(); //A sprite for every bar

7
8
		bar.graphics.beginFill(xmlFile.children()[i].@color); //Gets the color of the bar from the xml

9
		bar.graphics.drawRect(0, 0, xmlFile.@width, xmlFile.children()[i].@value); //Creates the bar according to the xml specified width

10
		bar.graphics.endFill();
11
12
		bar.x = 40 + (xmlFile.@width * i) + (10*i); //Bar position

13
		bar.y = 270 - bar.height;
14
15
		var val:TextField = new TextField(); //A TextField to display the value

16
17
		val.defaultTextFormat = tf;
18
		val.autoSize = TextFieldAutoSize.RIGHT;
19
		val.text = xmlFile.children()[i]. @ value; //Gets the value from xml

20
21
		val.x = 55 + (xmlFile.@width * i) + (10*i); //Textfield position

22
		val.y = 255 - bar.height;
23
24
		tween = new Tween(bar,"height",Strong.easeOut,0,bar.height,1,true); //Animates the bar

25
				
26
		addChild(bar); //Adds the sprites to stage

27
		addChild(val);
28
	}
29
}

Step 14: Info Area

Information about the graph will be displayed in the top-right corner, this function will take care of that.

1
2
private function displayNames():void
3
{
4
	for (var i:int = 0; i < totalBars; i++)
5
	{
6
		var color:Sprite = new Sprite(); //Creates sprites and textfields for every bar

7
		var names:TextField = new TextField();
8
9
		names.defaultTextFormat = tf;
10
		names.autoSize = TextFieldAutoSize.LEFT;
11
		names.text = xmlFile.children()[i]. @ name;
12
13
		/* Position */
14
15
		names.x = 500;
16
		names.y = 30 + (20 * i);
17
18
		/* Color squares */
19
20
		color.graphics.beginFill(xmlFile.children()[i].@color);
21
		color.graphics.drawRect(0, 0, 10, 10);
22
		color.graphics.endFill();
23
24
		color.x = 490;
25
		color.y = 31 + (20 * i);
26
27
		addChild(names);
28
		addChild(color);
29
	}
30
}

Step 15: Document Class

Go back to the .Fla file and in the Properties Panel add "Graph" in the Class field to make this the Document Class.

Conclusion

Test your movie and see your graph appear on stage.

You can customize your graphs in many ways, using the XML file, and also adding new features with ActionScript. Try it!

I hope you liked this tutorial, Thanks for reading.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.