Create a Dynamic Bar Graph Generator Using XML + AS3

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 600×300 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:

<?xml version="1.0"?>
	<graphs width="50">
		<graph name="Yellow" value="50" color="0xFDC13E"/>
		<graph name="Blue" value="80" color="0x25B7E2"/>
		<graph name="Green" value="30" color="0xB8CF36"/>
		<graph name="Red" value="10" color="0xE7473F"/>
	</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

package
{

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).

import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;
import flash.net.URLLoader;
import flash.net.URLRequest;
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.

public class Graph extends Sprite
{

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.

private var graphContainer:Sprite = new Sprite();
private var xmlFile:XML; //The XML Object to parse the XML file
private var urlLoader:URLLoader = new URLLoader(); //The file loader
private var totalBars:int; //Stores the number of bars of the graph

private var tween:Tween; //A Tween object for animation
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.

public function Graph():void
{
	/* Text Format */

	tf.color = 0x666666;
	tf.size = 12;
	tf.font = "Helvetica";

	createGraphContainer();
	loadXML();
	createBars();
}

Step 10: Graph Container

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

private function createGraphContainer():void
{
	graphContainer.graphics.lineStyle(1, 0x9C9C9E);
	graphContainer.graphics.moveTo(30, 30);
	graphContainer.graphics.lineTo(30, 270);
	graphContainer.graphics.lineTo(570, 270);

	addChild(graphContainer);
}

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.

private function loadXML(file:String = "graph.xml"):void //Your xml data file
{
	urlLoader.load(new URLRequest(file)); //Loads the file in the parameter
	urlLoader.addEventListener(Event.COMPLETE, parseXML); Calls a function when the load is complete
}

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.

private function parseXML(e:Event):void
{
	xmlFile = new XML(e.target.data);
	totalBars = xmlFile.children().length();

	createBars();
	displayNames();
}

Step 13: Create Bars

This code handles the bar creation.

private function createBars():void
{
	for (var i:int = 0; i < totalBars; i++)//This for checks the number of bars in the xml
	{
		var bar:Sprite = new Sprite(); //A sprite for every bar

		bar.graphics.beginFill(xmlFile.children()[i].@color); //Gets the color of the bar from the xml
		bar.graphics.drawRect(0, 0, xmlFile.@width, xmlFile.children()[i].@value); //Creates the bar according to the xml specified width
		bar.graphics.endFill();

		bar.x = 40 + (xmlFile.@width * i) + (10*i); //Bar position
		bar.y = 270 - bar.height;

		var val:TextField = new TextField(); //A TextField to display the value

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

		val.x = 55 + (xmlFile.@width * i) + (10*i); //Textfield position
		val.y = 255 - bar.height;

		tween = new Tween(bar,"height",Strong.easeOut,0,bar.height,1,true); //Animates the bar

		addChild(bar); //Adds the sprites to stage
		addChild(val);
	}
}      

Step 14: Info Area

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

private function displayNames():void
{
	for (var i:int = 0; i < totalBars; i++)
	{
		var color:Sprite = new Sprite(); //Creates sprites and textfields for every bar
		var names:TextField = new TextField();

		names.defaultTextFormat = tf;
		names.autoSize = TextFieldAutoSize.LEFT;
		names.text = xmlFile.children()[i]. @ name;

		/* Position */

		names.x = 500;
		names.y = 30 + (20 * i);

		/* Color squares */

		color.graphics.beginFill(xmlFile.children()[i].@color);
		color.graphics.drawRect(0, 0, 10, 10);
		color.graphics.endFill();

		color.x = 490;
		color.y = 31 + (20 * i);

		addChild(names);
		addChild(color);
	}
}

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.

Add Comment

Discussion 56 Comments

Comment Page 1 of 21 2
  1. Ian Lockhear says:

    Power of AS3 with XML put to good use.
    People who don’t even want to learn flash and just want to make an animated graph to impress there old-time boss will make usage of this. Then learn flash from seeing the usefulness.
    Nice tut

  2. Kyle Buchanan says:

    This is a great start. So much can be done with this as a base. You could easily subclass the Graph class with a Bar Chart class, Scatter Plot class, or a Pie class. Thanks for the great foundation.

  3. Excellent start, I like it. Is similar google graphics statistics. Regards!

  4. Sani says:

    Nice tut….clear and easy to follow….

    • Karl Macklin says:

      Yeah it would looks so much nicer if the bar was animated from the bottom and up, not the other way around

      • Alan says:

        I dont know much about co-ordinate systems in Flash, but you could draw the bar with negative height value and position it without the height appended.

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

        bar.y = 270;

  5. Erick says:

    i,c your next tutorial should be a dynamic xml gallery with dynamic texts. that is what most people need, but only find dinky tutorials online.

  6. Artkabis says:

    good job !!!

    I also released a tutorial on creating a graph with management xml, but the hold is fully managed from as3 : http://www.weecast.fr/flash_actionscript/graphiques-dynamique-avec-gestion-xml-flash-actionscript,5964.html

    ps: sorry for my English

  7. André says:

    Yeah, it´s inverted, but this is amazing, thanks a lot for this tutorial!!

  8. keseth says:

    Very Nice:D

    Any way This can be manipulated to create a 100% stacked bar graph?

  9. jamie says:

    Excellent easy and easy to follow.

    Thanks

  10. dave says:

    Hi,

    Was wondering what the php code would be draw this graph. for example I have 3 columns each with a value in a mysql database that I want to draw into the graph

  11. Brian says:

    Very great indeed!.

    What i want see from you is to write an article on how to perform linecharts.

    That would be awesome!

    Thanks!

  12. i declare u god of flash .

    how did u make mxml file .

  13. LOlitta says:

    I tried to follow this tut and do my first Bar chart with AS3 but i had problems
    every time the program show me this errors’ report
    Please help me to success my program and thx (soory for my english :P)
    (i used the adobe flash CS4 Professional and MS XML)
    waiting for a swift reply

  14. LOlitta says:

    Following are the errors:
    1084: Erreur de syntaxe : leftparen est attendu devant the.
    1084: Erreur de syntaxe : identifier est attendu devant rightbrace.
    1084: Erreur de syntaxe : rightparen est attendu devant rightbrace.
    1084: Erreur de syntaxe : rightbrace est attendu devant end of program.

  15. MrSurr says:

    So the only thing I found problematic was the height. Anyone got an auto height solution for graphing items where “value” can range from 10,000 to 1000000?

    • MrSurr says:

      Did you ever find an answer to this, I am having this exact same problem now! Any information you can give me would be GREAT!
      Thank.

  16. Ngộ Độc says:

    On step 11:

    fix:
    urlLoader.addEventListener(Event.COMPLETE, parseXML); Calls a function when the load is complete

    to
    urlLoader.addEventListener(Event.COMPLETE, parseXML); //Calls a function when the load is complete

    because ” Calls a function when the load is complete ” is note

  17. פרקטים says:

    i had good time to read it :)

  18. thank you about your post’ it will help me soon .

  19. wow fanatastic page
    it s very good to all

  20. בלונים says:

    wow what a post
    good

  21. nice
    i think is the best post in ste

  22. bat says:

    tank you frind :)

  23. thank u’ its always nice to read :)

  24. it’s always nice to know it! 10′s

  25. משחקים says:

    wow man, this is one of the best tuts out there! thanks

  26. thank u, u r the greatest!

  27. Hi, cool post!
    Thanks for sharing :)

  28. the best post i ever read!! thank u!

  29. I used ur code, and the bar looks great.

    Thank U!

  30. Thank you for the post, really helpfull.

  31. זכוכית says:

    nice idea :) u got abig like

  32. בלוגים says:

    really cool
    i didn’t know xml can use for this.
    thank u!

  33. yeahh it’s really cool to use this for it.!

  34. שולחנות שמחק לאירועים אצלכם באירוע

  35. משלוחי בלונים לכל אירוע אצלכם בשמחה

  36. lalita says:

    Thank you!
    Now I’m trying to make this horizontal…but I need some help.Any ideas?

  37. Thank you! I really needed to add some bars to my site, but JavaScript solutions not so easy to implement and they are not so flexible.

  38. מנעולן says:

    we used the code, and looks really great.

    Thank you!

  39. amsale says:

    we used the code, and looks really great.

    Thank you!

  40. we use this xml code , thank you very nice things to put in our site

    Eli

  41. I’m using a XML code now for my site and it is very helpful. Thanks a lot.

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.