Saltar al contenido

Cómo agregar porcentaje y total en la leyenda de gráficos circulares de Google

Nuestro equipo especializado despúes de días de trabajo y recopilar de información, dimos con la respuesta, esperamos que resulte de gran utilidad en tu plan.

Solución:

Mira este ejemplo de violín. Es su código con leyenda adjunta (idea del primer comentario, cálculo total y algunos errores menores corregidos).

La idea básica es establecer legend opción de gráfico para none y luego tienes que construir tu propia leyenda.

Si carga ese código en el navegador, la leyenda se colocará a la derecha, pero debe establecer las reglas CSS adecuadas para que todo salga bien (no estoy tan familiarizado con CSS). Pero tienes la idea básica de cómo hacerlo.

Y para diferentes conjuntos de colores de leyenda, puede verificar color brewer

Hay una forma de hacer esto utilizando la leyenda incorporada. Esencialmente, puede utilizar el hecho de que el gráfico se representa en SVG y puede seleccionar y modificar elementos en SVG de la misma manera que selecciona elementos HTML normales. La idea básica eres tú:

  1. Seleccione las etiquetas en la leyenda del gráfico y recorra la colección en iteración. Son etiquetas de texto, y puede averiguar el selector usando Firebug o Chrome Developer Tools.
  2. Use el índice del elemento para seleccionar el total de la fila asociada en la tabla de datos del gráfico (o inserte su lógica aquí para calcular cualquier valor que desee mostrar).
  3. Modifique el texto del elemento de etiqueta para agregar su valor calculado.

Vea mi Codepen para un ejemplo de trabajo: http://codepen.io/breich/pen/mVPJwo

/**
 * Selector for chart element.
 */
var chartSelector = '#chart';

/**
 * Selector used to get label elements inside the rendered chart.
 * Your mileage may vary if you configure your chart different than
 * me. Use Firebug or Developer Tools to step through the SVG and
 * determine your label selector.
 */
var labelSelector = '> g:eq(1) g text';

/**
 * This is our data. For simplicity sake, doing inline and not AJAX.
 */
var data = [
  [ 'Apples', 10],
  [ 'Oranges', 20 ],
  [ 'Peaches', 30 ],
  [ 'Pears', 40 ],
  [ 'Bananas', 50 ]
];

// Load Google Charts 
google.load('visualization', '1.1',  packages: ['corechart', 'line'] );

// Callback when API is ready
google.setOnLoadCallback(function() 

  /*
   * Setup the data table with your data. 
   */
  var table = new google.visualization.DataTable(
    cols : [
       id : 'name', label : 'Name', type : 'string' ,
       id : 'value', label : 'Value', type : 'number' 
    ]
  );

  // Add data to the table
  table.addRows( data );

  // Google Charts needs a raw element. I'm using jQuery to get the chart
  // Container, then indexing into it to get the raw element.
  var chartContainer = $(chartSelector)[0];

  // Create the Google Pie Chart
  var chart = new google.visualization.PieChart(chartContainer);

  // Draw the chart.
  chart.draw(table,  title : 'Classifications' );

  /*
   * This is the meat and potatoes of the operation. We really require
   * two things: #1) A selector that will get us a list of labels in the
   * legend, and #2) The DataTable powering the chart.  We'll cycle
   * through the labels, and use their index to lookup their value.
   * If you have some higher-level math you need to do to display a
   * different value, you can just replace my logic to get the count
   * with your's.
   */

  // The  element rendered by Google Charts
  var svg = $('svg', chartContainer );

  /*
   * Step through all the labels in the legend.
   */
  $(labelSelector, svg).each(function (i, v) 

    /*
     * I'm retrieving the value of the second column in my data table,
     * which contains the number that I want to display. If your logic
     * is more complicated, change this line to calculate a new total.
     */
    var total = table.getValue(i, 1);

    // The new label text.
    var newLabel = $(this).text() + '(' + total + ')';

    // Update the label text.
    $(this).text( newLabel );
  );

);

Puede hacer esto creando una columna para información sobre herramientas y usar su primera columna como leyenda. Mira este violín

var dataArray = [
    ['Frank.net Life Cover', 226],
    ['Frank.net Hospital Cash Back', 147],
    ['Frank.net Salary Protection', 228],
    ['King Price Car Insurance', 328],
    ['Momentum Medical Aid', 493],
    ['Oplan Health Cover', 185,],
    ['Youi Quote', 33],
];

var total = getTotal(dataArray);

// Adding tooltip column  
for (var i = 0; i < dataArray.length; i++) 
  dataArray[i].push(customTooltip(dataArray[i][0], dataArray[i][1], total));


// Changing legend  
for (var i = 0; i < dataArray.length; i++) 
  dataArray[i][0] = dataArray[i][0] + " " + 
      dataArray[i][1] + " requests, " + ((dataArray[i][1] / total) * 100).toFixed(1) + "%"; 


// Column names
dataArray.unshift(['Goal Name', 'No. of times Requested', 'Tooltip']);

var data = google.visualization.arrayToDataTable(dataArray);

Utilizando arrayToDataTable, debe establecer la información sobre herramientas de la función en la columna "Información sobre herramientas":

data.setColumnProperty(2, 'role', 'tooltip');
data.setColumnProperty(2, 'html', true);

Nota: si está creando el dataTable dinámicamente solo llame addColumn con esta firma:

data.addColumn('type': 'string', 'role': 'tooltip', 'p': 'html': true);

Y en opciones agregue tooltip: isHtml: true :

var options = 
    title: 'Most Requested Sponsors',
    width: 900,
    height: 400,
    tooltip:  isHtml: true 
;

Comentarios y puntuaciones

Si para ti ha sido provechoso este post, te agradeceríamos que lo compartas con otros entusiastas de la programación y nos ayudes a extender este contenido.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *