如何在D3饼图中将对象数组绑定到圆弧? [英] How can I bind an array of objects to arcs in a D3 pie chart?

查看:66
本文介绍了如何在D3饼图中将对象数组绑定到圆弧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个饼图,并且我的数据采用JSON形式:

I'm building a pie chart and my data is in the form of a JSON:

[
  {
    "Stage":"birth",
    "Avg":19071
  },
 { 
   //
 }
]

我不知道如何使用数据功能将json数据绑定到我的选择中.所以这对我不起作用:

I don't know how I should use the data function to bind that json data to my selection. So this is not working for me:

pie = d3.layout.pie();

arcs = svg.selectAll("g.arc") 
  .data(pie(data)) // ?
  .enter()
  .append("g")
  .attr({
    "transform" : "translate(" + outerRadius + "," + outerRadius + ")",
    "class": function(d,i){
      console.log(d3.keys(d));
    }       
  });

pie.sort(null);

//Draw arc paths  
arcs.append("path")
  .attr({
    "d": arc,
    "class" : "arc"
  });

如何使用.data以便可以访问json中的每个键/值对?抱歉,如果这是一个非常简单的问题,但是在这种情况下,我无法确定按键的工作原理.

How do I use .data so I can have access to each key/value pair in the json? Sorry if this is a really simple question but I can't wrap my head around how keys work in this case.

推荐答案

您需要给layout.pie一个


完整的工作示例:


Full working sample:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <script>
    var data = [{
      "Stage": "birth",
      "Avg": 19071
    }, {
      "Stage": "death",
      "Avg": 10000
    }];
    
    var svg = d3.select('body')
      .append('svg')
      .attr('width', 500)
      .attr('height', 500);
      
    var colors = d3.scale.category10();

    var pie = d3.layout
      .pie()
      .sort(null)
      .value(function(d) {
        return d.Avg;
      })

    var arc = d3.svg.arc()
      .outerRadius(90)
      .innerRadius(0);

    var arcs = svg.selectAll("g.arc")
      .data(pie(data)) //<-- this is fine
      .enter()
      .append("g")
      .attr({
        "transform": "translate(" + 100 + "," + 100 + ")",
        "class": function(d, i) {
          return d.data.Stage; //<-- after pieing the data, the raw data is then in the data property
        }
      });

    //Draw arc paths  
    arcs.append("path")
      .attr({
        "d": arc,
        "class": "arc"
      })
      .style('fill', function(d,i){
        return colors(i);
      })
  </script>
</body>

</html>

这篇关于如何在D3饼图中将对象数组绑定到圆弧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆