2011-08-31 16 views
8

Estoy buscando una manera de generar gráficos circulares usando SVG.Generación de gráficos SVG en JavaScript

Los números que tengo son bastante simple - sólo los porcentajes, una serie de números que, obviamente, se suman a 100.

tengo una comprensión básica de SVG, pero no se me ocurre cómo traducir estos números en coordenadas significativas para usar en la etiqueta de ruta

¿Alguien me puede indicar una utilidad o biblioteca útil, o dar alguna pista sobre cómo puedo usar porcentajes para dibujar un gráfico circular, en JavaScript?

+0

Relacionados (pero no duplicados): [SVG vs lona para gráficos circulares] (http://stackoverflow.com/questions/5936474/pie-bar-line-svg-vml-better-than-canvas); [Gráficos circulares SVG usando Ruby] (http://stackoverflow.com/questions/4358390/svg-piechart-with-ruby); [XSLT lib para gráficos SVG] (http://stackoverflow.com/questions/2504130/looking-for-a-library-of-xslt-to-create-svg-charts). – Phrogz

Respuesta

6

Éstos son algunos más:

  • Elycharts (basado en jQuery y Rafael, licencia MIT)
  • ZingCharts (, ha backends comerciales/Flash SVG/VML/HTML5)
  • Grafico (basado en Prototype y Rafael, licencia MIT)
  • d3.js (muy buena biblioteca de gráficos interactivos y dinámicos, como el MIT-license)

trato de recopilar enlaces a todas las bibliotecas de gráficos SVG here.

3

Raphael es una muy buena biblioteca de dibujo SVG; en particular, supera a las demás porque en versiones anteriores de IE, automáticamente vuelve a utilizar VML, y por lo tanto funciona en IE desde la versión 6 y superior, así como en todos los otros navegadores mainstream.

Tiene una biblioteca gráfica separada, llamada gRaphael. Esto hace todos los tipos de gráficos habituales (pies, líneas, barras, etc.) y puede animarlos también.

Si eso no es suficiente, es bastante fácil usar la biblioteca principal de Raphael para rodar la suya, es muy fácil de usar.

17

Créditos a https://stackoverflow.com/a/3642265/309483 y http://jbkflex.wordpress.com/2011/07/28/creating-a-svg-pie-chart-html5/ (tenga en cuenta que el último tiene un error, fija aquí)

function makeSVG(tag, attrs) { 
 
    var el= document.createElementNS('http://www.w3.org/2000/svg', tag); 
 
    for (var k in attrs) 
 
     if (attrs.hasOwnProperty(k)) el.setAttribute(k, attrs[k]); 
 
    return el; 
 
} 
 

 
function drawArcs(paper, pieData){ 
 
    var total = pieData.reduce(function (accu, that) { return that + accu; }, 0); 
 
    var sectorAngleArr = pieData.map(function (v) { return 360 * v/total; }); 
 

 
    var startAngle = 0; 
 
    var endAngle = 0; 
 
    for (var i=0; i<sectorAngleArr.length; i++){ 
 
     startAngle = endAngle; 
 
     endAngle = startAngle + sectorAngleArr[i]; 
 

 
     var x1,x2,y1,y2 ; 
 

 
     x1 = parseInt(Math.round(200 + 195*Math.cos(Math.PI*startAngle/180))); 
 
     y1 = parseInt(Math.round(200 + 195*Math.sin(Math.PI*startAngle/180))); 
 

 
     x2 = parseInt(Math.round(200 + 195*Math.cos(Math.PI*endAngle/180))); 
 
     y2 = parseInt(Math.round(200 + 195*Math.sin(Math.PI*endAngle/180))); 
 

 
     var d = "M200,200 L" + x1 + "," + y1 + " A195,195 0 " + 
 
       ((endAngle-startAngle > 180) ? 1 : 0) + ",1 " + x2 + "," + y2 + " z"; 
 
     //alert(d); // enable to see coords as they are displayed 
 
     var c = parseInt(i/sectorAngleArr.length * 360); 
 
     var arc = makeSVG("path", {d: d, fill: "hsl(" + c + ", 66%, 50%)"}); 
 
     paper.appendChild(arc); 
 
     arc.onclick = (function (originalData) { 
 
      return function(event) { 
 
      alert("Associated pie piece data: " + originalData); 
 
      } 
 
     })(pieData[i]); 
 
    } 
 
} 
 
var svgdoc = document.getElementById("s"); 
 
drawArcs(svgdoc, [52,15,20,80]); // here is the pie chart data 
 

 
// You can attach additional content (from e.g. AJAX) like this: 
 
var parser = new DOMParser(); 
 
var docToEmbed = parser.parseFromString(
 
    "<svg xmlns='http://www.w3.org/2000/svg'><text x='50' y='50' fill='black'>hi</text></svg>", 
 
    "image/svg+xml"); 
 
Array.prototype.slice.call(docToEmbed.documentElement.childNodes).forEach(function(elem) { 
 
    svgdoc.appendChild(document.importNode(elem, true)); 
 
});
#con { 
 
    resize:both; 
 
    overflow:hidden; 
 
    display:inline-block; 
 
    width:20em; 
 
    height:20em; 
 
    padding:0.5em; 
 
}
<div id="con"> 
 
<!-- the div container is of course optional. It is used with 
 
    {width,height}="100%" below to make the chart resizable. --> 
 
<svg width="100%" height="100%" id="s" 
 
xmlns="http://www.w3.org/2000/svg" viewbox="0 0 400 400"> 
 
    <style type="text/css"> 
 
    path:hover { 
 
     opacity: 0.8; 
 
    } 
 
    </style> 
 
</svg> 
 
</div>

+0

esto es genial thx – Prozi

+0

¡Oh, definitivamente eres un caballero y un erudito! –

Cuestiones relacionadas