Learning Ext JS 3

Charts with ExtJS Más videos

Descripción del tema

One of the new functionalities in the new version of the ExtJS library is the possibility to create charts easily, you can create bar chats, linear charts and pie charts from a store.

Resources

To start with this tutorial you need to download the resources, which has a HTML document that only includes the ExtJS library and an empty JS, which will be the file where we're going to write the code for the charts.

Packaging the tutorial

Before we start the tutorial you need to package the code we will be writing, we already know the advantages of doing it, since we've studied about it.
//the namespace for this tutorial
Ext.ns('com.quizzpot.tutorial');

com.quizzpot.tutorial.Charts = {
	init: function(){
		//We are going to write the code here
	}
}

Ext.onReady(com.quizzpot.tutorial.Charts.init,com.quizzpot.tutorial.Charts);
The previous code must be written in the file "chart.js".

Defining the information to be displayed

Now we're going to define the information we need to display on the chart, for this example I'm going to display a chart of the different JavaScript libraries and quantity of users of their communities (this information is fake since it's just an example). Don't forget that this information could come from a database or some other source and it can be interpreted in any format that is supported by the store (XML, JSON, Array), in this case the information will come from an array we define directly in the code.
//information to display in the chart
var data = [['Ext JS',115000],['jQuery',250100],['Prototype',150000],['mootools',75000],['YUI',95000],['Dojo',20000],['Sizzle',15000]];
		
//we create the Store that will manipulate the information
var store = new Ext.data.ArrayStore({
	fields:[{name:'framework'},{name:'users', type:'float'}]
});
store.loadData(data); // loading the information in the store
We have discussed the previous code in previous chapters so this must look familiar to you.

The charts

This component is an adaptation of the library YUI, which uses a "swf" (flash movie) to generate the images of the chart, it is customizable because we can change the aspect of the chart (colors, typography, styles). You can find the components in the package "Ext.chart" so I recommend you to read the documentation.

Bar Chart

Let's create a bar chart with the information we have in the store:
var columnChart = new Ext.chart.ColumnChart({
	store: store,
	//url:'../ext-3.0-rc1/resources/charts.swf',
	xField: 'framework',
	yField: 'users'
});
The basic configuration properties are only those three, we can add more properties by specifying the "url" of the file "swf", since is the one in charge to display the chart; this is really important if we don't want to our application to search the "swf" from Yahoo and it's actually required to specify the "url" if we don't have Internet access. With the property "xField" we define where the graph should be positioned on the X axis, meanwhile the property "yField" indicates the position for the Y axis, these two fields are required to create a Bar Chart. If we add the property "renderTo" we can render the chart in the screen, so it can look like like this:
Grfica

Bar Chart

Linear Chart

A linear chart is created the same way as the bar chart, we only need to use the component "LineChart" like this:
var lineChart = new Ext.chart.LineChart({
	store: store,
	xField: 'framework',
	yField: 'users'
});
This information is enough to create a basic linear chart; to render this chart on the screen we can use the property "render To".
Graph

Linear Chart

Pie Chart

The pie chart is created differently from the other charts because we don't have X and Y axis. A pie chart is created with percentages, the component "PieChart" handles everything, we only need to configure the next few lines:
var pieChart = new Ext.chart.PieChart({
	store: store,
	dataField: 'users', //information to display in the chart
	categoryField : 'framework' //tags or categories
});
In the previous code the property "dataField" contains the information that is going to be displayed in the chart and the property "categoryField" contains the categories that are being graphing, these two properties are very important to display the chart correctly.
Grfica

Pie Chart

Positioning the charts on the screen

At this point we are going to create the panels we need for each chart, we assign these panels to a main panel and we render it to the div "frame" we have in the HTML document; also we're going to make the panels collapsible.
var panel1 = new Ext.Panel({
	title: 'Column chart example',
	items:[columnChart]
});
	
var panel2 = new Ext.Panel({
	title: 'Line chart example',
	items:[lineChart]
});
		
var panel3 = new Ext.Panel({
	title: 'Pie chart example',
	items:[pieChart]
});
		
var main = new Ext.Panel({
	renderTo: 'frame',
	width:450,
	defaults: {
		height:250,
		collapsible: true,
		border:false,
		titleCollapse: true
	},
	items: [panel1,panel2,panel3]
});
The previous code generates the following screen.
Graph

Charts on ExtJS 3

We have seen the functionality of the panels before so you must be familiar with the previous code.

Conclusions

The ExtJS Framework provides charts that allow us to display information in a very simple way and we can integrate them easily with other components (panels, windows, forms, etc). In this tutorial we have seen something we can create using the new version of ExtJS, in future articles I will show you other components tha were added in this version. As always, questions or suggestions are welcome, so make sure to leave a comment or post it in the forum.

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?

26Comentarios

  • Avatar-10 Toshop 25/08/2009

    It makes cool looking charts.

    • Avatar-1 Daniel 25/01/2010

      Is it possible to merge the columns together?

      • Avatar-6 tobaonline 26/10/2010

        there are examples of other, more creative???

        • Avatar-5 pablo medici 22/12/2010

          Hi, great tutorial!, thanks!, I have it working on firefox and chrome but i'm having problems in internet explorer, it doesn't show the graphics, any idea? thanks!

          • Avatar-1 Fatih 22/12/2010

            Great introduction. Thanks

            • Avatar-6 bill 11/01/2011

              i can't able to show the chart!!! need help.

              • Avatar-1 Crysfel 18/01/2011

                Make sure you're setting the URL configuration to the right SWF in your own server. Best regards

                • Avatar-4 Tayyabah 18/03/2011

                  Can you please tell me how can I combine stackedbar and column charts together? As one of the extjs demo they have combined column and line chart together. I want to combine the column with stackedbar. Any help will be greatly appreciated.

                  • Avatar-6 Math 28/03/2011

                    U have to do something like this : var chart = new Ext.chart.ColumnChart({ store: chartStore, series: [{ type: 'line', displayName: 'name one', yField: 'data_one', style: { // color: 0xCCCCCC, // alpha:0, // fillColor: 0xCCCCCC, // fillAlpha:0 } },{ //type: 'line', displayName: 'name two', yField: 'data_two', style: { //alpha: 0 } }], xField: 'date' //yField: 'sms_amount' }); As u can see this is the ColumnChart object, but one of the series has type : line. In this way u can combine both, line and column chart in one graph. It would be the same if u have LineChart with the series of type: 'bar' Hope it helps. Regards

                    • Avatar-8 tiger5412 13/04/2011

                      hi ! how to display dynamic legends ?? for example ..from data Base .. need help

                      • Avatar-10 Chinmay 20/05/2011

                        Hi, I want to create a chart having data for number of weeks in x axis and multiple activities in y axis. now can i create such a chart using this library? each activities can have one or more sub activity and for each sub activity again we have the values for each of the weekdays of a week. Technically speaking need to show multiple charts in a single chart where x axis to common to all.

                        • Avatar-5 Ilham Meidi Brata 16/06/2011

                          How to change color style/themes on chart?

                          • Avatar-7 Math 01/07/2011

                            As in my previous post ffrom Mar 28, 2011 in style property you have to put object like this : style: { color: 0xCCCCCC, alpha:0, fillColor: 0xCCCCCC, fillAlpha:0 }

                            • Avatar-7 bindupavan 11/07/2011

                              can we pass the data values to chart dynamically by using component

                              • Avatar-2 mtfco 14/10/2011

                                is it possible to display data value in pie chart legend along with data field name? thx

                                • Avatar-10 mtfco 14/10/2011

                                  oops sorry, i meant displaying dataField along with categoryField in legend

                                  • Avatar-12 At 14/11/2011

                                    can we rotrait column chart? Regards, At

                                    • Avatar-12 Prostil 04/01/2012

                                      Hi, Nice tutorial. Can we download these charts a jpeg or png images? Something like AMCharts provides. Thank you.

                                      • Avatar-10 and 21/02/2012

                                        you can using the last version (Ext JS 4.1) still in beta version...

                                        • Avatar-2 NE 01/06/2012

                                          What should I do/which function should I use, if I want to read data from JSON Stirng which returns from another function?

                                          • Avatar-7 NE 01/06/2012

                                            Sorry I could not express my self I guess. Again! What should I do/which function should I use, if I want to read data from JSON Stirng which is returned by another function?

                                            • Avatar-1 Raj 07/06/2012

                                              How can I show Value on grids of bar chart.

                                              • Avatar-11 Sudha 20/06/2012

                                                Hi, The tutorial is good. Thanks for the nice informative blog.

                                                • Avatar-12 sadmer 20/05/2013

                                                  how to add highchart in extjs panel

                                                  • Avatar-2 elizabetha 30/12/2013

                                                    great tutorial!!! Excellent!!! I was looking for this. I want to know the diference between linear chart with pie chart. Thanks a lot

                                                    • Avatar-2 9825782274 27/09/2014

                                                      When I am trying to run above code i am getting error ct is null..

                                                      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.