KEMBAR78
JavaScript para Graficos y Visualizacion de Datos | PDF
JavaScript para
Gráficos y Visualización
      de Datos

   Nicolas Garcia Belmonte   -   @philogb
Uso estándares web para crear visualizaciones de datos.




                     @philogb
Soy el autor de dos frameworks de visualización en
                     JavaScript



     PhiloGL                 JavaScript InfoVis Toolkit
Visualización en la Web con JavaScript

                            Extraer
                            Gather       DB


Datos / Servidor /        Transformar
                           Transform     Python
    Cliente
                             Servir
                             Serve       JSON / Binary


                          Cargar Data
                           Load Datos    XHR2



                         Build Models
                         Crear Modelos   Workers / TypedArrays
     Viz / Cliente

                           Renderear
                            Render       WebGL / 2D Canvas


                          Interactuar
                            Interact     DOM Events / HTML Forms
Primer Ejemplo
Data Source
Video / Camera
                 Rendering
                  WebGL
  Interaction
     Forms
Recolección de Datos
                 HTML5 Video & Media Source
<video id="movie" autoplay controls class="shadows" width="480">
  <source src="movie/shrek.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
  <source src="movie/shrek.ogv" type='video/ogg; codecs="theora, vorbis"' />
</video>


var video = document.getElementById('movie');
video.play();
video.pause();
video.volume += 0.1;



navigator.getUserMedia('video', function(localMediaStream) {
    video.src = window.URL.createObjectURL(localMediaStream);
}, function() {
    //error...
});
Transformación de Datos
               Obtener pixel data usando 2D Canvas

<canvas id="pastie" width="50" height="50" style="display:none;"></canvas>



var canvas = document.getElementById('pastie'),
    ctx = canvas.getContext('2d'),
    rgbaArray;

ctx.drawImage( movie, 0, 0, 50, 50);

rgbaArray =  ctx.getImageData(0, 0, 50, 50).data;
Crear Modelos 3D
                               Web Workers

var worker = new Worker('task.js');

worker.addEventListener('message', function(e) {
    var models = e.data;
    //do something with the models once they're built...
}, false);

worker.postMessage();


//in task.js
self.addEventListener('message', function(e) {
    var models;
    //build models...
    self.postMessage(models);
});
Renderear la Escena
       Canvas / WebGL / PhiloGL

   function loop() {
     //send data to GPU
     program.setUniform('size', sizeValue);
     program.setBuffer('histogram', {
       value: new Float32Array(createColorArray(movie)),
       size: 1
     });
     //rotate histogram a little bit
     theta += 0.007;
     histogramModel.rotation.set(-Math.PI / 4, theta, 0.3);
     histogramModel.update();
     //clear the screen
     gl.clearColor(color, color, color, 1);
     gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
     //render the scene
     scene.render();
     //request next frame for loop
     Fx.requestAnimationFrame(loop);
   }
Segundo Ejemplo
Interaction
   Forms




       Rendering / Interaction
              WebGL


                Interaction
                   Forms
Datos
• 1200 estaciones de meteorología
• 72 horas de datos
• 5 variables - latitud, longitud, velocidad y
  dirección del viento, temperatura


   = 460.000 items
Datos
                    Datos Binarios

direction   speed   temperature   direction   speed   temperature

                     unsigned ints



                       [10, 1, 100, ...]


                            JSON
Datos
          Datos Binarios

             Binary           JSON

1500000

1125000

 750000

 375000

      0
                      Bytes
Cargar Datos
                       XHR2
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://some.binary.data/', true);

//track file loading progress
xhr.addEventListener('progress', function(e) {
    console.log(Math.round(e.loaded / e.total * 100));
}, false);

//set to receive array buffer
xhr.responseType = 'arraybuffer';

//get data when available
xhr.addEventListener('readystatechange', function(e) {
    if (xhr.readyState == 4 /* COMPLETE */) {
        if (xhr.status == 200 /* OK */) {
            //binary data here!
            handleBinaryData(xhr.response); //ArrayBuffer
        }                    
    }
}, false);

//send request
xhr.send();
Cargar Datos
Typed Arrays: Ultra rápidos Arrays

function handleBinaryData(arraybuffer) {
    var typedArray = new Uint16Array(arraybuffer);
    //do stuff like with a regular array
    for (var i = 0, l = typedArray.length; i < l; ++i) {
        typedArray[i] += 2;        
    }
}

                                     Uint8Array


                                    Float32Array
       ArrayBuffer

                                     Int16Array


                                        etc.
Interacción
                                 HTML5 Forms

     <input id='time' type='range' value='0' min='0' max='71' step='1'>


                 var slider = document.getElementById('time');

                 slider.addEventListener('change', function(e) {
                     var value = slider.valueAsNumer;
                 }, false);




Otros tipos: color, date, datetime, email, month, number, range, search, tel, time, url, week, etc.
  //Create application
  PhiloGL('canvasId', {
    program: {
      from: 'uris',
      vs: 'shader.vs.glsl',
                                  WebGL / PhiloGL
      fs: 'shader.fs.glsl'
    },                                            Rendering
    camera: {
      position: {
        x: 0, y: 0, z: -50
      }
    },
    textures: {
      src: ['arroway.jpg', 'earth.jpg']
    },
    events: {
      onDragMove: function(e) {
        //do things...
      },
      onMouseWheel: function(e) {
        //do things...
      }
    },
    onError: function() {
      alert("There was an error creating the app.");
    },
    onLoad: function(app) {
      /* Do things here */
    }
  });
Conclusión
                    En mi opinión:

   HTML5 APIs Puras
           +
        Polyfills
           +
                         >     Monolithic Application
                                  Frameworks
Lightweight Frameworks
Gracias!

@philogb

http://philogb.github.com/

JavaScript para Graficos y Visualizacion de Datos

  • 1.
    JavaScript para Gráficos yVisualización de Datos Nicolas Garcia Belmonte - @philogb
  • 2.
    Uso estándares webpara crear visualizaciones de datos. @philogb
  • 4.
    Soy el autorde dos frameworks de visualización en JavaScript PhiloGL JavaScript InfoVis Toolkit
  • 6.
    Visualización en laWeb con JavaScript Extraer Gather DB Datos / Servidor / Transformar Transform Python Cliente Servir Serve JSON / Binary Cargar Data Load Datos XHR2 Build Models Crear Modelos Workers / TypedArrays Viz / Cliente Renderear Render WebGL / 2D Canvas Interactuar Interact DOM Events / HTML Forms
  • 7.
  • 9.
    Data Source Video /Camera Rendering WebGL Interaction Forms
  • 10.
    Recolección de Datos HTML5 Video & Media Source <video id="movie" autoplay controls class="shadows" width="480">   <source src="movie/shrek.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />   <source src="movie/shrek.ogv" type='video/ogg; codecs="theora, vorbis"' /> </video> var video = document.getElementById('movie'); video.play(); video.pause(); video.volume += 0.1; navigator.getUserMedia('video', function(localMediaStream) {     video.src = window.URL.createObjectURL(localMediaStream); }, function() {     //error... });
  • 11.
    Transformación de Datos Obtener pixel data usando 2D Canvas <canvas id="pastie" width="50" height="50" style="display:none;"></canvas> var canvas = document.getElementById('pastie'),     ctx = canvas.getContext('2d'),     rgbaArray; ctx.drawImage( movie, 0, 0, 50, 50); rgbaArray =  ctx.getImageData(0, 0, 50, 50).data;
  • 12.
    Crear Modelos 3D Web Workers var worker = new Worker('task.js'); worker.addEventListener('message', function(e) {     var models = e.data;     //do something with the models once they're built... }, false); worker.postMessage(); //in task.js self.addEventListener('message', function(e) {     var models;     //build models...     self.postMessage(models); });
  • 13.
    Renderear la Escena Canvas / WebGL / PhiloGL   function loop() {     //send data to GPU     program.setUniform('size', sizeValue);     program.setBuffer('histogram', {       value: new Float32Array(createColorArray(movie)),       size: 1     });     //rotate histogram a little bit     theta += 0.007;     histogramModel.rotation.set(-Math.PI / 4, theta, 0.3);     histogramModel.update();     //clear the screen     gl.clearColor(color, color, color, 1);     gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);     //render the scene     scene.render();     //request next frame for loop     Fx.requestAnimationFrame(loop);   }
  • 14.
  • 16.
    Interaction Forms Rendering / Interaction WebGL Interaction Forms
  • 17.
    Datos • 1200 estacionesde meteorología • 72 horas de datos • 5 variables - latitud, longitud, velocidad y dirección del viento, temperatura = 460.000 items
  • 18.
    Datos Datos Binarios direction speed temperature direction speed temperature unsigned ints [10, 1, 100, ...] JSON
  • 19.
    Datos Datos Binarios Binary JSON 1500000 1125000 750000 375000 0 Bytes
  • 20.
    Cargar Datos XHR2 var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://some.binary.data/', true); //track file loading progress xhr.addEventListener('progress', function(e) {     console.log(Math.round(e.loaded / e.total * 100)); }, false); //set to receive array buffer xhr.responseType = 'arraybuffer'; //get data when available xhr.addEventListener('readystatechange', function(e) {     if (xhr.readyState == 4 /* COMPLETE */) {         if (xhr.status == 200 /* OK */) {             //binary data here!             handleBinaryData(xhr.response); //ArrayBuffer         }                         } }, false); //send request xhr.send();
  • 21.
    Cargar Datos Typed Arrays:Ultra rápidos Arrays function handleBinaryData(arraybuffer) {     var typedArray = new Uint16Array(arraybuffer);     //do stuff like with a regular array     for (var i = 0, l = typedArray.length; i < l; ++i) {         typedArray[i] += 2;             } } Uint8Array Float32Array ArrayBuffer Int16Array etc.
  • 22.
    Interacción HTML5 Forms <input id='time' type='range' value='0' min='0' max='71' step='1'> var slider = document.getElementById('time'); slider.addEventListener('change', function(e) {     var value = slider.valueAsNumer; }, false); Otros tipos: color, date, datetime, email, month, number, range, search, tel, time, url, week, etc.
  • 23.
      //Create application   PhiloGL('canvasId', {    program: {       from: 'uris',       vs: 'shader.vs.glsl', WebGL / PhiloGL       fs: 'shader.fs.glsl'     }, Rendering     camera: {       position: {         x: 0, y: 0, z: -50       }     },     textures: {       src: ['arroway.jpg', 'earth.jpg']     },     events: {       onDragMove: function(e) {         //do things...       },       onMouseWheel: function(e) {         //do things...       }     },     onError: function() {       alert("There was an error creating the app.");     },     onLoad: function(app) {       /* Do things here */     }   });
  • 24.
    Conclusión En mi opinión: HTML5 APIs Puras + Polyfills + > Monolithic Application Frameworks Lightweight Frameworks
  • 25.