d3具有一个对象键/值的饼图

时间:2017-11-14 23:11:42

标签: javascript d3.js charts

你好我对d3和javascript很新。我试图显示一个饼图,其中一个对象充满了多个键和值。

这是我的对象:

dataset Object { $Allied Health Professions, Dentistry, Nursing and Pharmacy: 4, $Psychology, Psychiatry and Neuroscience: 4, $Biological Sciences: 4, $General Engineering: 4, $Architecture, Built Environment and Planning: 4, $Geography, Environmental Studies and Archaeology: 4, $Business and Management Studies: 4, $Law: 4, $Social Work and Social Policy: 4, $Education: 4, 5 de plus… }

我的代码很长,文件很多,所以我认为链接它并不重要。

我成功加载了一个带有简单数组的饼图,但我不知道如何在这里访问这些值。

1 个答案:

答案 0 :(得分:3)

D3 data方法接受3件事:

  1. 数组;
  2. 一个功能;
  3. 没有
  4. 因此,您必须在对象数组中转换该对象,具有该类别的特定属性和该值的属性。例如:

    
    
    var obj = {
      "Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
      "Psychology, Psychiatry and Neuroscience": 4,
      "Biological Sciences": 4,
      "General Engineering": 4,
      "Architecture, Built Environment and Planning": 4
    };
    var data = [];
    for (var key in obj) {
      data.push({
        name: key,
        value: obj[key]
      })
    };
    console.log(data)
    
    
    

    这是一个基本的演示,其中包含一部分对象:

    
    
    var obj = {
      "Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
      "Psychology, Psychiatry and Neuroscience": 4,
      "Biological Sciences": 4,
      "General Engineering": 4,
      "Architecture, Built Environment and Planning": 4
    };
    var data = [];
    for (var key in obj) {
      data.push({
        name: key,
        value: obj[key]
      })
    };
    var arc = d3.arc().outerRadius(100).innerRadius(0);
    var pie = d3.pie().value(function(d) {
      return d.value
    });
    var colors = d3.scaleOrdinal(d3.schemeCategory10)
    var svg = d3.select("svg")
      .append("g")
      .attr("transform", "translate(100,100)")
    svg.selectAll(null)
      .data(pie(data))
      .enter()
      .append("path")
      .attr("d", arc)
      .style("fill", function(d, i) {
        return colors(i)
      })
    
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <svg width="200" height="200"></svg>
    &#13;
    &#13;
    &#13;