d3 Pie chart with one object key /value

Hello I am quite new with d3 and javascript. I am trying to display a pie chart with one object fill with mutiple key and value.

Here my object :

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… }

My code is quite long and in mutiple files so I don't think it's relevant to link it.

I succed to load a pie chart with a simple array but i do not know how to acces the values here.

1 answer

  • answered 2017-11-14 23:53 Gerardo Furtado

    D3 data method accepts 3 things:

    1. An array;
    2. A function;
    3. Nothing;

    Therefore, you have to convert that object in an array of objects, with a specific property for the category and a property for the value. For instance:

    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)

    Here is a basic demo with a portion of your object:

    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>