Learning Ext JS 3

Chart series Más videos

Descripción del tema

In a previous tutorial we talked about the new component "Chart", we learned how to build a simple chart, a pie chart, linear chart and bar chart. Today we will learn how to build a chart with a series of data. In this tutorial we are going to build a chart series that can help us visualize the total of "earnings" in a year of a certain movie genre. I have prepared a demo to show the final result of this tutorial.
Series

Building a Chart series

Resources

Before we start with the tutorial you need to download the resources, which only contain a HTML and a JS file.

Defining the information for the chart

The first thing we need to do is define the location of the information; for this tutorial I'll just define the information directly in a "Store" by using a JavaScript array, but you can get the information from a database and use Ajax to load the Store, remember that we have studied this previously.
var store = new Ext.data.JsonStore({
	fields: ['year', 'comedy', 'action', 'drama', 'thriller'],
	data: [
			{year: 2004, comedy: 39000000, action: 53890000, drama: 38450000, thriller: 32060000},
			{year: 2005, comedy: 34000000, action: 23890000, drama: 18450000, thriller: 20060000},
			{year: 2006, comedy: 56703000, action: 38900000, drama: 12650000, thriller: 21000000},
			{year: 2007, comedy: 42100000, action: 50410000, drama: 25780000, thriller: 23040000},
			{year: 2008, comedy: 38910000, action: 56070000, drama: 24810000, thriller: 26940000}
		]
});
In the store I have simulated the gross of certain movies genres through the past years, so this information is enough to start building the chart.

Building the chart

Let's build a column chart and use a window to display the chart on the screen. Let's build a chart for the "comedy" genre at this moment.
var chart = new Ext.chart.ColumnChart({
	store: store, 		// Step 1
	xField: 'year',		//Step 2
	yField: 'comedy'	//Step 3
});
In the first step we assign the store to the chart, this step is very important because we're relating the information (in the store) with the chart component. In the second step we defined the field of the store (that we defined in the previous step) that will be used as the "X" axis. In the third step we define the field of the store that will be used as the "Y" axis. Now we need to create a container in order to render the chart, in this case we will use a window with the following configuration:
var win = new Ext.Window({
	title: 'Chart series example',
	width:550,
	height:320,
	layout:'fit',
	items: chart
});

win.show();
At this point we have enough information to build a chart, so if you update your browser you will see the following image:
Series

A Simple chart

Adding series

At this moment we've built the chart with only one category, to include more categories in this chart we need to use the property "series" and remove the property "yField" since it will be determined by each series.
var chart = new Ext.chart.ColumnChart({
	store: store,
	xField: 'year',
	//yField: 'comedy' 		//Step 1
	series:[				//Step 2
		{yField:'comedy'},	//Step 3
		{yField:'action'},
		{yField:'drama'},
		{yField:'thriller'}
	]
});
In the first step we removed the property "yField" so we can assign it later. In the second step we created an array with the series we'll use, inside of this array we will write the configuration for each series, just remember that we can define different properties for each series. In the last step we have the configuration for each series, I kept the configuration very simple to make it understandable and I defined the property "yField" by assigning the field where the value is going to be taken.
Series

Displaying the Series

As you can see, is very easy to build a chart that will help us visualize the comparison between different categories, in this example I used movie genres but you can use any kind of information.

Adding a legend

To improve our chart we can add a legend with the meaning of each bar and color, so go ahead and add the following code:
var chart = new Ext.chart.ColumnChart({
	store: store,
	xField: 'year',
	series:[
		{yField:'comedy'},
		{yField:'action'},
		{yField:'drama'},
		{yField:'thriller'}
	],
	extraStyle:{			//Step 1
		legend:{		//Step 2
			display: 'bottom'//Step 3
		}
	}
});
In the first step we define the extra styles we will use for the chart, the properties defined in this object will overwrite the default properties. In the second step we specify that we will add styles to the legend. In the third step we only specify that we want to display the legend at the bottom part of the chart, we can position the caption on "top", "right", "left" or "bottom". To see the changes we just need to refresh the screen and we will see something similar to the following image.
Series

Showing a legend at the bottom part of the chart

Changing the text of the legend

If you looked carefully at the previous screen you probably noticed that only numbers were shown on the legend, this is not really helpful to the user, so we need to assign a text that will tell the user the meaning of the columns and colors.
{yField:'comedy',displayName:'Comedy'},
{yField:'action',displayName:'Action'},
{yField:'drama',displayName:'Drama'},
{yField:'thriller',displayName:'Thriller'}
In every series we added the property "displayName", by doing this we now can assign a text to the legend and the user will understand better the chart.
Series

Showing texts on the legend instead of numbers

Formatting the axes

What we're going to do now is formatting the text that is being displayed on the axis; on the axis "Y" we need to have the format currency, to do this we need to add the following configuration inside of the definition of ColumnChart.
yAxis: new Ext.chart.NumericAxis({
	labelRenderer: Ext.util.Format.usMoney
})
The property "labelRenderer" accepts a function that will process the content that is going to be displayed by each item of the axis, this functionality is very similar to the "renderer" we use in grids. Now let's modify the axis "X" assigning a personalized function.
xAxis: new Ext.chart.CategoryAxis({
	labelRenderer:  this.customFormat
})
Then we will define the function "customFormat" that will process the content that we want to display, this function has to belong to the principal object.
customFormat:function(value){
	return 'Year: '+value;
}
Series

You can see that we have used two different component for the axis: “Ext.chart.NumericAxis” to create a numerical range and “Ext.chart.CategoryAxis” to use the categories we defined in the store.

Conclusions

Is very easy to build charts with ExtJS, the component is very flexible because it allow us to easily customize it. I tried to make this tutorial very simple, only using the basic configurations to achieve the correct functionality but I recommend you to play with this component and create different kind of charts. If you're still not following us on Twitter(@quizzpot), I recommend you to do it so you can be updated. You can also subscribe to our Feeds or receive them on your mail.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

8Comentarios

  • Avatar-12 big 06/03/2010

    if i want to use php to do series chart(multiple line). how to do it?

    • Avatar-10 Marcus Boos 09/06/2010

      @big: take a look at the ExtJs API Docs. "Ext.data.JsonStore" can load its data by Ajax from a remote file. This file my also be a PHP file which generates the JSON. Also take a look at json_encode() at php.net.

      • Avatar-9 Sleeptillseven 24/09/2010

        Thanks. That's what I was looking for. Unfortunately, whenever there is something fancy with charts in ExtJs, one has to check the ExtJS API, Yahoo UI and several blog until the charts talks magic.

        • Avatar-5 Delvia 07/01/2011

          Thanks, this is a very nice tutorial. Found it really useful.

          • Avatar-5 Delvia_Bles 07/01/2011

            the customFormat is not getting applied. plz reply!

            • Avatar-2 ssk 16/02/2011

              Thanks.It helps me a lot.But when I tried to find the series config option in the Extjs API,I could not find it.

              • Avatar-7 ?ukasz 19/08/2011

                very usefull tutorial :) I'm beginner in Ext JS and a I have to create the chart from *.json file. If anyone can help? I will be very thankfull PS: I tried to do this with documentations but without success

                • Avatar-6 enrique 22/08/2011

                  I need more information, about to jsonStore from data php. thanks.

                  Instructor del curso

                  Crysfel3

                  Autor: Crysfel Villa

                  Software engineer with more than 7 years of experience in web development.

                  Descarga Código Fuente Ver Demostración

                  Regístrate a este curso

                  Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

                  Tendrás acceso a descargar los videos, códigos y material adicional.

                  Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

                  Llevarás un registro de tu avance.