ayushgp
ayushgp

Reputation: 5101

D3 - Creating multiple circles elements for every entry in dataset

I have the following dataset:

    "data":[
            ["1951","306","27","159","34","82","4"],
            ["1956","426","41","203","47","119","16"],
            ["1959","562","67","267","48","148","32"],
            ["1960","605","76","282","54","157","36"],
            ["1961","665","88","310","57","168","42"],
            ["1962","749","116","340","60","189","44"],
            ["1963","847","140","375","63","215","54"],
            ...

The first entry in each array is the year. I have created 2 coordinate axes w.r.t. this data. Now for each of these entries I want to create 6 circle elements. How can I do this using a variation of the following line:

var circles = svg.selectAll("circle")
                .data(data.data)
                .enter()
                .append("circle");

var circleAttr = circles. //Attributes defined here

Upvotes: 2

Views: 2335

Answers (1)

Dogbert
Dogbert

Reputation: 222398

You can use the .selectAll(...).data(...).enter(...).append(...) pattern twice in a row, passing a function to .data the second (and later) time, where you accept the data from the previous level and return an array of data items for that level.

Here's a little example using your data:

var colors = d3.scale.category10().domain([1951, 1963]);

var data = [
  ["1951", "306", "27", "159", "34", "82", "4"],
  ["1956", "426", "41", "203", "47", "119", "16"],
  ["1959", "562", "67", "267", "48", "148", "32"],
  ["1960", "605", "76", "282", "54", "157", "36"],
  ["1961", "665", "88", "310", "57", "168", "42"],
  ["1962", "749", "116", "340", "60", "189", "44"],
  ["1963", "847", "140", "375", "63", "215", "54"]
];

d3.select("body")
  .append("svg")
  .attr("width", 1000)
  .attr("height", 1000)
  .selectAll("g")
  .data(data)
  .enter()
  .append("g")
  .selectAll("circle")
  .data(function(d) {
    var year = +d[0];
    return d.slice(1).map(function(value) {
      return {
        year: year,
        value: +value
      };
    });
  })
  .enter()
  .append("circle")
  .attr("r", 2)
  .attr("cx", function(d) {
    return d.value;
  })
  .attr("cy", function(d) {
    return d.value;
  })
  .attr("fill", function(d) {
    return colors(d.year);
  });

Demo: https://jsfiddle.net/Dogbert/vvera4w9/

Upvotes: 2

Related Questions