Open Flash Chart Helper: gráficos al estilo Cake

[Este es un artículo que he escrito en inglés para el Bakery de CakePHP y que traduzco acá para la comunidad en español] Open Flash Chart es una solución interesante para dibujar gráficos a partir de datos en tu aplicación. Este artículo introduce un Helper de CakePHP para hacer la labor de dibujar gráficos más sencilla.

Open Flash Chart es una solución interesante para dibujar gráficos a partir de datos en tu aplicación. Este artículo introduce un Helper de CakePHP para hacer la labor de dibujar gráficos más sencilla.

Requisitos

Para hacer uso de este helper, primero debes descargar el archivo zip de Open Flash Chart desde http://teethgrinder.co.uk/open-flash-chart/download.php.

Dentro hay dos archivos necesarios para usar este helper:

  • open-flash-chart.swf coloca este archivo en el directorio [app]/webroot/
  • php-ofc-library/open-flash-chart.php coloca este archivo en el directorio [app]/vendors

El Helper:

Para obtener el helper descargalo del repositorio subversion:

svn co http://svn2.assembla.com/svn/cakeopenflashchart/trunk/flash_chart.php

Si no usas svn puedes descargarlo, manualmente, de ese url también

Uso

Ahora, para usar este helper haz como con cualquier otro:

  1. var $uses = array(‘FlashChart’);

Los siguientes ejemplos están todos colocados en un archivo de vista [app]/views/pages/charts.ctp (por lo tanto debes modificar PagesController para que use el Helper) y generan datos al azar (pero usar una base de datos es igual de fácil).

Ejemplo 1 - Gráficos de Barra

  1. <?php
  2. // Sets height and width
  3. $flashChart->begin(400, 250);
  4. // Title
  5. $flashChart->title(‘Example 1 - Bars: Hits per Day’);
  6. // Configure Grid style and legends
  7. $flashChart->configureGrid(
  8.     array(
  9.         ‘x_axis’ => array(
  10.             ’step’ => 1,
  11.             ‘legend’ => ‘Day’
  12.         ),
  13.         ‘y_axis’ => array(
  14.             ‘legend’ => ‘#Hits’,
  15.         )
  16.     )
  17. );
  18. // Prepare some random data (10 points)
  19. $random_hits = array();
  20. for ($i=0; $i < 10; $i++) {
  21.     $random_hits[] = rand(10,100);
  22. }
  23. // Register each data set with its information.
  24. $data = array(
  25.     ‘Hits’ => array(
  26.         ‘color’ => ‘#afe342′,
  27.         ‘font_size’ => 11,
  28.         ‘data’ => $random_hits,
  29.         ‘graph_style’ => ‘bar’,
  30.     )
  31. );
  32. $flashChart->setData($data);
  33.  
  34. // Set Ranges in the chart
  35. $flashChart->setRange(‘y’, 0, 100);
  36. $flashChart->setRange(‘x’, 0, 10);
  37.  
  38. // Show the graph
  39. echo $flashChart->render();
  40. ?>

Este ejemplo genera un gráfico de barras sencillo con los datos generados al azar en un ciclo. Para generar otro gráfico en la misma vista es importante reiniciar los datos del helper invocando el método FlashChartHelper::begin

Nota: cambia ‘graph_style’ => ‘bar’ a alguno de los siguientes para ver todos los tipos de gráfico de barra disponibles

  • ‘graph_style’ => ‘bar_sketch’
  • ‘graph_style’ => ‘bar_glass’
  • ‘graph_style’ => ‘bar_filled’
  • ‘graph_style’ => ‘bar_3D’
  • ‘graph_style’ => ‘bar_fade’

Ejemplo 2 - Gráficos de Líneas

Para graficar líneas en vez de barras, el único cambio necesario al ejemplo anterior es sustituir ‘graph_style’ => ‘bar’ por alguno de los siguientes

  • ‘graph_style’ => ‘line’
  • ‘graph_style’ => ‘line_hollow’
  • ‘graph_style’ => ‘line_dot’
  1. <?php
  2. // Sets height and width
  3. $flashChart->begin(400, 250);
  4. // Title
  5. $flashChart->title(‘Example 2 - Lines: Hits per Day’);
  6. // Configure Grid style and legends
  7. $flashChart->configureGrid(
  8.     array(
  9.         ‘x_axis’ => array(
  10.             ’step’ => 1,
  11.             ‘legend’ => ‘Day’
  12.         ),
  13.         ‘y_axis’ => array(
  14.             ‘legend’ => ‘#Hits’,
  15.         )
  16.     )
  17. );
  18. // Prepare some random data (10 points)
  19. $random_hits = array();
  20. for ($i=0; $i < 10; $i++) {
  21.     $random_hits[] = rand(10,100);
  22. }
  23. // Register each data set with its information.
  24. $data = array(
  25.     ‘Hits’ => array(
  26.         ‘color’ => ‘#00aa42′,
  27.         ‘font_size’ => 11,
  28.         ‘data’ => $random_hits,
  29.         ‘graph_style’ => ‘lines’,
  30.     )
  31. );
  32. $flashChart->setData($data);
  33.  
  34. // Set Ranges in the chart
  35. $flashChart->setRange(‘y’, 0, 100);
  36. $flashChart->setRange(‘x’, 0, 10);
  37.  
  38. // Show the graph
  39. echo $flashChart->render();
  40. ?>

Ejemplo 3 - Gráficos de Puntos

Este tipo de gráfico usa una sintaxis diferente para definir los datos a graficar. Requiere que los datos se especifiquen en puntos (pares x,y), aquí está el ejemplo:

  1. <?php
  2. // Sets height and width
  3. $flashChart->begin(400, 250);
  4. // Title
  5. $flashChart->title(‘Example 3 - Scatter: Some Random Points’);
  6. // Configure Grid style and legends
  7. $flashChart->configureGrid(
  8.     array(
  9.         ‘x_axis’ => array(
  10.             ’step’ => 1,
  11.             ‘legend’ => ‘Day’
  12.         ),
  13.         ‘y_axis’ => array(
  14.             ‘legend’ => ‘#Hits’,
  15.         )
  16.     )
  17. );
  18. // Prepare some random data (10 points)
  19. $random_points = array();
  20. for ($i=0; $i < 10; $i++) {
  21.     // Each point is represented as a pair (x,y)
  22.     $random_points[] = array(‘x’ => $i, ‘y’ => rand(0,100));
  23. }
  24. // Register each data set with its information.
  25. $data = array(
  26.     ‘Random Points’ => array(
  27.         ‘color’ => ‘#00aa42′,
  28.         ‘font_size’ => 11,
  29.         ‘data’ => $random_points,
  30.         ‘graph_style’ => ’scatter’
  31.     )
  32. );
  33. $flashChart->setData($data);
  34.  
  35. // Set Ranges in the chart
  36. $flashChart->setRange(‘y’, 0, 100);
  37. $flashChart->setRange(‘x’, 0, 10);
  38.  
  39. // Show the graph
  40. echo $flashChart->render();
  41. ?>

Ejemplo 4 - Gráficos de Torta

Este tipo de gráfico también usa una sintaxis distinta, aquí está el ejemplo:

  1. <?php
  2. $flashChart->begin(400, 250);
  3. $flashChart->title(‘Example 4 - Pie Chart: My imaginary Browser Stats’);
  4. $browser_data = array(
  5.     ‘Firefox’ => array(
  6.         ‘value’ => 30
  7.     ),
  8.     ‘Opera’ => array(
  9.         ‘value’ => 7
  10.     ),
  11.     ‘IE’ => array(
  12.         ‘value’ => 38
  13.     ),
  14.     ‘Other’ => array(
  15.         ‘value’ => 25
  16.     )
  17. );
  18. $flashChart->pie($browser_data);
  19.  
  20. echo $flashChart->render();
  21. ?>

Nota: El Helper de Flash Chart selecciona automáticamente los colores, para cada sección del gráfico, si no los estableces explícitamente.

Ejemplo 5 - Gráficos Mixtos

Open Flash Chart permite varios conjuntos de datos dentro de un mismo gráfico, puedes mezclar gráficos de barras, líneas y puntos, aquí hay un ejemplo que extienden al primer ejemplo presentado:

  1. <?php
  2. // Sets height and width
  3. $flashChart->begin(400, 250);
  4. // Title
  5. $flashChart->title(‘Example 5 - Mixed: Hits per Day vs. # Visits’);
  6. // Configure Grid style and legends
  7. $flashChart->configureGrid(
  8.     array(
  9.         ‘x_axis’ => array(
  10.             ’step’ => 1,
  11.             ‘legend’ => ‘Day’
  12.         ),
  13.         ‘y_axis’ => array(
  14.             ‘legend’ => ‘#Hits’,
  15.         )
  16.     )
  17. );
  18. // Prepare some random data (10 points)
  19. $visits = array();
  20. $random_hits2 = array();
  21. for ($i=0; $i < 10; $i++) {
  22.     $visits[] = rand(10,50);
  23.     $random_hits2[] = rand(50,100);
  24. }
  25. // Register each data set with its information.
  26. $data = array(
  27.     ‘Hits’ => array(
  28.         ‘color’ => ‘#afe342′,
  29.         ‘font_size’ => 11,
  30.         ‘data’ => $random_hits2,
  31.         ‘graph_style’ => ‘line_dot’,
  32.     ),
  33.     ‘Visits’ => array(
  34.         ‘color’ => ‘#324aef’,
  35.         ‘font_size’ => 11,
  36.         ‘data’ => $visits,
  37.         ‘graph_style’ => ‘bar’,
  38.     )
  39. );
  40. $flashChart->setData($data);
  41.  
  42. // Set Ranges in the chart
  43. $flashChart->setRange(‘y’, 0, 100);
  44. $flashChart->setRange(‘x’, 0, 10);
  45.  
  46. // Show the graph
  47. echo $flashChart->render();
  48. ?>

Resultados

Los resultados de estos ejemplos pueden encontrarlos en http://aikon.com.ve/flashchart/

¿Qué Falta?

En estos momentos, hay dos tipos de gráfico que Open Flash Chart ofrece y que el Helper no implementa:

Algunas posibles mejoras:

  • Escribir funciones de más alto nivel que encapsulen muchas de las líneas usadas en los ejemplos.
  • Selección automática de los rangos de los ejes.

Si algo falta

Reportalo: http://trac2.assembla.com/cakeopenflashchart/newticket

Recibe otros artículos como este automáticamente
Suscríbete vía RSS a aikon.com.ve || ¿Qué es RSS?

Tags: , ,

BlinkbitsBlinkListsBlogLinesBlogmarksBuddymarksCiteULikeCo.mmentsDel.icio.usDiggDiigo

FarkFeed Me LinksFurlGoogleLinkagogoma.gnoliaMister WongNewsvinePropellerRawsugar

RedditRojoSimpySphinnSpurlSquidooStumbleUponTailrankTechnoratiYahoo

Comentarios

» 3 Personas han comentado sobre “Open Flash Chart Helper: gráficos al estilo Cake”

  1. José Lorenzo:

    Hola, me ha gustado mucho tu helper. Creo que lo usaré en varios proyectos y en mi Tesis.

    ¿Hay alguna manera de imprimir los Gráficos generados en flash?

    Gracias por compartir…

  2. Joaquín Windmüller:

    Hola José.

    Parece que es un problema de Flash, al menos en Firefox.

    He probado en Safari y Opera en Mac OS X y sí imprime correctamente los gráficos. Parece ser un problema conocido: https://bugs.launchpad.net/firefox/+bug/117036

  3. straighten » links for 2008-04-02:

    [...] Open Flash Chart Helper: gráficos al estilo Cake (tags: cakephp Chart swf Flash) | | | Yahoo!ブックマークに登録 | | | [...]

Deja tu respuesta

requerido

requerido

Nota: mantente dentro del tema y se respetuoso.