Sameh K. Mohamed
Sameh K. Mohamed

Reputation: 2333

D3 Plot array of circles

I've tried the circle plot example as the following:

  var x=20, y=20, r=50;
  var sampleSVG = d3.select("#viz")
  .append("svg")
  .attr("width", 800)
  .attr("height", 600);    

  sampleSVG.append("circle")
  .style("stroke", "gray")
  .style("fill", "white")
  .attr("r",  r)
  .attr("cx", x)
  .attr("cy", y);

But I want to figure out how to plot without a loop a sequence of circles from an array like:

  data = [
          [10,20,30],
          [20,30,15],
          [30,10,25]
         ];

Upvotes: 1

Views: 2669

Answers (1)

icanc
icanc

Reputation: 3577

Maybe this example could help?

var data = [
    [10,20,30],
    [20,30,15],
    [30,10,25]
];

var height = 300,
    width = 500;

var svg = d3.select('body').append('svg')
    .attr('height', height)
    .attr('width', width)
  .append('g')
    .attr('transform', 'translate(30, 30)');

// Bind each nested array to a group element.
// This will create 3 group elements, each of which will hold 3 circles.
var circleRow = svg.selectAll('.row')
    .data(data)
  .enter().append('g')
    .attr('transform', function(d, i) {
        return 'translate(30,' + i * 60 + ')';
    });

// For each group element 3 circle elements will be appended.
// This is done by binding each element in a nested array to a
// circle element.
circleRow.selectAll('.circle')
    .data(function(d, i) { return data[i]; })
  .enter().append('circle')
    .attr('r', function(d) { return d; })
    .attr('cx', function(d, i) { return i * 60; })
    .attr('cy', 0);

Live Fiddle

Upvotes: 2

Related Questions