Intervalos

Descripción general

Los gráficos de Google pueden mostrar intervalos alrededor de una serie. Se pueden usar para representar intervalos de confianza, valores mínimos y máximos en torno a un valor, muestreo de percentil o cualquier otro elemento que requiera un margen variable en torno a una serie.

Existen seis estilos de intervalo: línea, barra, caja, barra, punto y área. A continuación, se muestran ejemplos de cada uno. En cada ejemplo, usaremos el mismo conjunto de datos, que aquí se muestra sin intervalos:

El gráfico anterior es simple: tiene siete series de datos, todas con la misma importancia. En lo que sigue, supondremos que la primera serie es la principal y que las otras seis se comparan con ella a través de intervalos.

Intervalos de línea

A veces, los intervalos de línea se usan para representar la varianza de varios experimentos. En el siguiente gráfico, se ilustra una serie principal y los intervalos a su alrededor.

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('number', 'x');
        data.addColumn('number', 'values');
        data.addColumn({id:'i0', type:'number', role:'interval'});
        data.addColumn({id:'i1', type:'number', role:'interval'});
        data.addColumn({id:'i2', type:'number', role:'interval'});
        data.addColumn({id:'i2', type:'number', role:'interval'});
        data.addColumn({id:'i2', type:'number', role:'interval'});
        data.addColumn({id:'i2', type:'number', role:'interval'});
  
        data.addRows([
            [1, 100, 90, 110, 85, 96, 104, 120],
            [2, 120, 95, 130, 90, 113, 124, 140],
            [3, 130, 105, 140, 100, 117, 133, 139],
            [4, 90, 85, 95, 85, 88, 92, 95],
            [5, 70, 74, 63, 67, 69, 70, 72],
            [6, 30, 39, 22, 21, 28, 34, 40],
            [7, 80, 77, 83, 70, 77, 85, 90],
            [8, 100, 90, 110, 85, 95, 102, 110]]);
  
        // The intervals data as narrow lines (useful for showing raw source data)
        var options_lines = {
            title: 'Line intervals, default',
            curveType: 'function',
            lineWidth: 4,
            intervals: { 'style':'line' },
            legend: 'none'
        };
  
        var chart_lines = new google.visualization.LineChart(document.getElementById('chart_lines'));
        chart_lines.draw(data, options_lines);
      }
    </script>
  </head>
  <body>
    <div id="chart_lines" style="width: 900px; height: 500px;"></div>
  </body>
</html>
  

En los datos anteriores, puedes ver que adjuntamos tres identificadores diferentes a la serie complementaria: i0, i2 y i3. Podemos usarlos para aplicar diseños diferentes a esas series; a continuación, les asignamos diferentes colores y grosores.

Nota: En general, no es adecuado volver a usar los ID como se indicó anteriormente, ya que i2 se usa cuatro veces. Funciona, pero es posible que cambiemos este comportamiento en el futuro.

La única diferencia está en las siguientes opciones:

    var options_lines = {
        title: 'Line intervals, tailored',
        lineWidth: 4,
        curveType:'function',
        interval: {
            'i0': { 'style':'line', 'color':'#D3362D', 'lineWidth': 0.5 },
            'i1': { 'style':'line', 'color':'#F1CA3A', 'lineWidth': 1 },
            'i2': { 'style':'line', 'color':'#5F9654', 'lineWidth': 2 },
        },
        legend: 'none',
    };

Intervalos de barras

Los intervalos de barras crean barras de error alrededor de tus datos. La primera y la última columna del intervalo se dibujan como barras anchas paralelas al eje del dominio, y las columnas internas se dibujan como "ticks" más cortos. Se agrega un "stick" para unir las barras anchas (si estas dos barras tienen el mismo valor, la barra se renderiza como un punto, a menos que la opción pointSize sea cero).

El ancho de las barras horizontales que corresponden a la primera y la última columna se controla con intervals.barWidth, y el ancho de las barras horizontales que corresponden a las columnas internas se controla con intervals.shortBarWidth. Cuando se omitan, obtendrás un gráfico como el anterior con las siguientes opciones:

    var options_bars = {
        title: 'Bars, default',
        curveType: 'function',
        series: [{'color': '#D9544C'}],
        intervals: { style: 'bars' },
        legend: 'none',
    };

Intervalos

Intervalos de cuadros renderizaba columnas en tu tabla de datos como un conjunto de rectángulos anidados: la primera y última columna forman el rectángulo más externo, y las columnas internas se renderizan como rectángulos más oscuros dentro del cuadro contenedor.

A continuación, te mostramos cómo especificar los intervalos de cuadro:

    var options = {
        series: [{'color': '#1A8763'}],
        intervals: { style: 'boxes' },
        legend: 'none',
    };

Puedes destacar más los cuadros con las opciones intervals.lineWidth y intervals.barWidth:

Las opciones relevantes son las siguientes:

    var options = {
        title:'Boxes, thick',
        curveType:'function',
        lineWidth: 4,
        series: [{'color': '#1A8763'}],
        intervals: { 'lineWidth':2, 'barWidth': 0.5, style: 'boxes' },
        legend: 'none',
    };

Intervalos de ajuste

Los intervalos de los intervalos muestran pares de columnas como un conjunto de parámetros paralelos al eje de destino. Una barra con una altura de cero se renderiza como un punto, que se puede suprimir si estableces la opción pointSize en cero.

Puedes crearlos con un style de 'sticks':

    var options_sticks = {
        title:'Sticks, default',
        curveType:'function',
        series: [{'color': '#E7711B'}],
        intervals: { style: 'sticks' },
        legend: 'none',
    };

Intervalos de puntos

Los intervalos de puntos muestran los datos de intervalo como círculos pequeños:

El tamaño de los puntos se puede controlar con la opción intervals.pointSize. Aquí es 2:

    var options_points = {
        title:'Points, default',
        curveType:'function',
        lineWidth: 4,
        series: [{'color': '#D3362D'}],
        intervals: { 'style':'points', pointSize: 2 },
        legend: 'none',
    };

Así se ve en el paso 8:

Intervalos de área

Un intervalo de área renderiza los datos de intervalo como un conjunto de áreas sombreadas anidadas. La anidación de pares de columnas es similar a la de los intervalos de caja, excepto que se requiere un número par de columnas.

Para ello, se debe configurar style como 'area':

    var options = {
        title:'Area, default',
        curveType:'function',
        series: [{'color': '#F1CA3A'}],
        intervals: { 'style':'area' },
        legend: 'none',
    };

Cómo combinar estilos de intervalo

Para una personalización aún mayor, puedes combinar los estilos de intervalos dentro de un gráfico.

A continuación, se muestra un gráfico en el que se combinan intervalos de áreas y barras:

En el gráfico anterior, especificamos un style de 'bars' para los intervalos etiquetados con i0 y i1, y un estilo 'area' para i2. Luego, usamos pointSize para limitar las barras:

    var options = {
        title:'Bar/area interval chart',
        curveType:'function',
        intervals: { 'color':'series-color' },
        interval: {
            'i0': { 'color': '#4374E0', 'style':'bars', 'barWidth':0, 'lineWidth':4, 'pointSize':10, 'fillOpacity':1 },
            'i1': { 'color': '#E49307', 'style':'bars', 'barWidth':0, 'lineWidth':4, 'pointSize':10, 'fillOpacity':1 },
            'i2': { 'style':'area', 'curveType':'function', 'fillOpacity':0.3 }},
        legend: 'none',
    };

Este es un gráfico de líneas de intervalo de barras con los intervalos de i2 representados como barras:

    var options = {
        title:'Sticks, horizontal',
        curveType:'function',
        lineWidth: 4,
        series: [{'color': '#E7711B'}],
        intervals: { 'lineWidth': 4, 'barWidth': 0.5 },
        interval: {
            'i2': { 'style':'sticks', 'color':'grey', 'boxWidth': 2.5,
            'lineWidth': 1 }
        },
        legend: 'none',
    };

Este es un gráfico de líneas de intervalo que usa cuadros de opacidad baja para colocar intervalos seleccionados en el fondo:

    // Focus is the error bars, but boxes are visible in the background.
    var options_boxes_background = {
        title:'Background boxes',
        curveType:'function',
        lineWidth: 4,
        series: [{'color': '#1A8763'}],
        intervals: { 'lineWidth':2, 'barWidth': 0.5 },
        interval: {
            'i2': { 'style':'boxes', 'color':'grey', 'boxWidth': 2.5,
            'lineWidth': 0, 'fillOpacity': 0.2 }
        },
        legend: 'none',
    };

Podemos crear un gráfico de intervalos de "puntos y bigotes" especificando un estilo 'points' de baja opacidad para un intervalo junto con un boxWidth:

    var options = {
        title:'Points and whiskers',
        curveType:'function',
        lineWidth: 4,
        series: [{'color': '#D3362D'}],
        intervals: { 'lineWidth':2, 'barWidth': 0.5 },
        interval: {
            'i2': { 'style':'points', 'color':'grey', 'pointSize': 10,
            'lineWidth': 0, 'fillOpacity': 0.3 }
        },
        legend: 'none',
    };

Diagrama de cajas

Por último, según el gráfico de “puntos y bigotes” anterior, podemos usar intervalos de caja y barras para crear un gráfico de caja básico.

Opciones
      var options = {
          title:'Box Plot',
          height: 500,
          legend: {position: 'none'},
          hAxis: {
            gridlines: {color: '#fff'}
          },
          lineWidth: 0,
          series: [{'color': '#D3362D'}],
          intervals: {
            barWidth: 1,
            boxWidth: 1,
            lineWidth: 2,
            style: 'boxes'
          },
          interval: {
            max: {
              style: 'bars',
              fillOpacity: 1,
              color: '#777'
            },
            min: {
              style: 'bars',
              fillOpacity: 1,
              color: '#777'
            }
          }
      };
    
Cuerpo completo de la secuencia de comandos
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawBoxPlot);

    function drawBoxPlot() {

      var array = [
        ['a', 100, 90, 110, 85, 96, 104, 120],
        ['b', 120, 95, 130, 90, 113, 124, 140],
        ['c', 130, 105, 140, 100, 117, 133, 139],
        ['d', 90, 85, 95, 85, 88, 92, 95],
        ['e', 70, 74, 63, 67, 69, 70, 72],
        ['f', 30, 39, 22, 21, 28, 34, 40],
        ['g', 80, 77, 83, 70, 77, 85, 90],
        ['h', 100, 90, 110, 85, 95, 102, 110]
      ];

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'x');
      data.addColumn('number', 'series0');
      data.addColumn('number', 'series1');
      data.addColumn('number', 'series2');
      data.addColumn('number', 'series3');
      data.addColumn('number', 'series4');
      data.addColumn('number', 'series5');
      data.addColumn('number', 'series6');

      data.addColumn({id:'max', type:'number', role:'interval'});
      data.addColumn({id:'min', type:'number', role:'interval'});
      data.addColumn({id:'firstQuartile', type:'number', role:'interval'});
      data.addColumn({id:'median', type:'number', role:'interval'});
      data.addColumn({id:'thirdQuartile', type:'number', role:'interval'});

      data.addRows(getBoxPlotValues(array));

      /**
       * Takes an array of input data and returns an
       * array of the input data with the box plot
       * interval data appended to each row.
       */
      function getBoxPlotValues(array) {

        for (var i = 0; i < array.length; i++) {

          var arr = array[i].slice(1).sort(function (a, b) {
            return a - b;
          });

          var max = arr[arr.length - 1];
          var min = arr[0];
          var median = getMedian(arr);

          // First Quartile is the median from lowest to overall median.
          var firstQuartile = getMedian(arr.slice(0, 4));

          // Third Quartile is the median from the overall median to the highest.
          var thirdQuartile = getMedian(arr.slice(3));

          array[i][8] = max;
          array[i][9] = min
          array[i][10] = firstQuartile;
          array[i][11] = median;
          array[i][12] = thirdQuartile;
        }
        return array;
      }

      /*
       * Takes an array and returns
       * the median value.
       */
      function getMedian(array) {
        var length = array.length;

        /* If the array is an even length the
         * median is the average of the two
         * middle-most values. Otherwise the
         * median is the middle-most value.
         */
        if (length % 2 === 0) {
          var midUpper = length / 2;
          var midLower = midUpper - 1;

          return (array[midUpper] + array[midLower]) / 2;
        } else {
          return array[Math.floor(length / 2)];
        }
      }

      var options = {
          title:'Box Plot',
          height: 500,
          legend: {position: 'none'},
          hAxis: {
            gridlines: {color: '#fff'}
          },
          lineWidth: 0,
          series: [{'color': '#D3362D'}],
          intervals: {
            barWidth: 1,
            boxWidth: 1,
            lineWidth: 2,
            style: 'boxes'
          },
          interval: {
            max: {
              style: 'bars',
              fillOpacity: 1,
              color: '#777'
            },
            min: {
              style: 'bars',
              fillOpacity: 1,
              color: '#777'
            }
          }
      };

      var chart = new google.visualization.LineChart(document.getElementById('box_plot'));

      chart.draw(data, options);
    }