在 JavaScript 中生成 SVG 图表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7261318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:30:02  来源:igfitidea点击:

SVG chart generation in JavaScript

javascriptchartssvg

提问by BusterLuke

I'm looking for a way to generate pie charts using SVG.

我正在寻找一种使用 SVG 生成饼图的方法。

The numbers I have are simple enough - just percentages, an array of numbers that obviously add up to 100.

我的数字很简单——只是百分比,一组显然加起来等于 100 的数字。

I have a basic understanding of SVG, but I can't think how to translate these numbers into meaningful coordinates to use in the path tag

我对 SVG 有基本的了解,但我想不出如何将这些数字转换为有意义的坐标以在路径标签中使用

Can anyone point me to a useful utility or library, or give any hints as to how I could use percentages to draw a pie chart - in JavaScript?

任何人都可以指出一个有用的实用程序或库,或者就我如何使用百分比绘制饼图提供任何提示 - 在 JavaScript 中?

回答by Janus Troelsen

Credits to https://stackoverflow.com/a/3642265/309483and http://jbkflex.wordpress.com/2011/07/28/creating-a-svg-pie-chart-html5/(note that the last one has a bug, fixed here)

归功于https://stackoverflow.com/a/3642265/309483http://jbkflex.wordpress.com/2011/07/28/creating-a-svg-pie-chart-html5/(注意最后一个有一个错误,在这里修复)

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>

回答by Erik Dahlstr?m

Here are a few more:

这里还有一些:

  • Elycharts(based on jQuery and Rapha?l, MIT license)
  • ZingCharts(commercial, has SVG/VML/HTML5/Flash backends)
  • Grafico(based on Prototype and Rapha?l, MIT license)
  • d3.js(very nice library for interactive and dynamic graphs, MIT-like license)
  • Elycharts(基于 jQuery 和 Rapha?l,MIT 许可)
  • ZingCharts(商业版,具有 SVG/VML/HTML5/Flash 后端)
  • Grafico(基于 Prototype 和 Rapha?l,MIT 许可证)
  • d3.js(非常好的交互式和动态图形库,类似 MIT 的许可证

I try to collect links to all svg graphing libraries here.

我尝试在此处收集指向所有 svg 图形库的链接。

回答by Spudley

Raphaelis a very good SVG drawing library -- in particular, it beats the others because in older versions of IE, it automatically falls back to using VML, and therefore it works in IE from version 6 and up, as well as in all other mainstream browsers.

Raphael是一个非常好的 SVG 绘图库——特别是,它击败了其他人,因为在旧版本的 IE 中,它会自动回退到使用 VML,因此它可以在 IE 6 及更高版本以及所有其他版本中使用主流浏览器。

It has a separate graphing library, called gRaphael. This does all the usual graph types (pies, lines, bars, etc), and can animate them too.

它有一个单独的图形库,称为gRaphael。这可以完成所有常见的图形类型(饼图、线条、条形等),并且也可以为它们设置动画。

If those aren't enough, it's easy enough to use the main Raphael library to roll your own - it's very easy to use.

如果这些还不够,那么使用主要的 Raphael 库来推出您自己的库很容易 - 它非常易于使用。

回答by Chad

The best (IMO): Highcharts

最好的(IMO):Highcharts

Others I have heard about:

我听说过的其他人: