D3 Plot array of circles

北慕城南 提交于 2020-01-03 03:18:09

问题


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]
         ];

回答1:


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



来源:https://stackoverflow.com/questions/22767949/d3-plot-array-of-circles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!