John
John

Reputation: 495

Drawing D3 chart from array of arrays of objects

I have the following data:

var dataset = [[[1, 2], [1, 4]], [[5, 6], [9, 11]], [[5, 2], [15, 20]]];

and another small array of colors:

var color = ['#1f78b4', '#a6cee3', '#33a02c', '#b2df8a', '#b15928', '#ffff99',
            '#6a3d9a', '#cab2d6', '#ff7f00', '#fdbf6f', '#e31a1c', '#fb9a99']; 

I want to build a point chart in D3, but for every dataset[i], the points should have different colors. After calculating the scales, and drawing the axes, I get to the last part to draw the points of the chart, and this is what I came to:

for (var n = 0; n < dataset.length; n++) {
    svg.selectAll("circle")
    .data(dataset[n])
    .enter()
    .append("circle")
    .attr("id", n)
    .attr("fill", color[n])
    .attr("cx", function (d) {
        return xScale(d[1]);
    })
    .attr("cy", function (d) {
        return yScale(d[0]);
    })
    .attr("r", rad);
}

Basically what I want is for each data collection in the "dataset", the points to have different colors (for example the [[1, 2], [1, 4]] to have the #1f78b4 color, for the [[5, 6], [9, 11]] to have the next color.. and so on). But when I run the code, it draws only the first collection from the 'dataset', ignoring the other two... Did someone encounter such a problem? How can it be solved?

Upvotes: 0

Views: 1752

Answers (1)

Mark
Mark

Reputation: 108512

As I said in my comment:

While an explicit loop works here, a nested selection is more appropriate.

<!DOCTYPE html>
<html>

<head>
  <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>

<body>
  <script>
    var dataset = [
      [
        [1, 2],
        [1, 4]
      ],
      [
        [5, 6],
        [9, 11]
      ],
      [
        [5, 2],
        [15, 20]
      ]
    ];

    var color = ['#1f78b4', '#a6cee3', '#33a02c', '#b2df8a', '#b15928', '#ffff99',
      '#6a3d9a', '#cab2d6', '#ff7f00', '#fdbf6f', '#e31a1c', '#fb9a99'
    ];

    var svg = d3.select('body')
      .append('svg')
      .attr('width', 300)
      .attr('height', 300);

    // set up some scales
    var x = d3.scale.linear().range([0, 300]).domain([0, 22]);
    var y = d3.scale.linear().range([0, 300]).domain([0, 22]);
    
    var g = svg.selectAll(".collection") //<-- group per outer array
      .data(dataset)
      .enter()
      .append("g")
      .attr("class", "collection");
      
    g.selectAll("point") //<-- here the nest
      .data(function(d){
        return d; //<-- this is your array of points
      })
      .enter()
      .append("circle")
      .attr("class", "point")
      .attr("cx", function(d){
        return x(d[0]);
      })
      .attr("cy", function(d){
        return y(d[1]);
      })
      .attr("r", 5)
      .style("fill", function(d,i,j){
        return color[j]; //<-- j in index of the group
      })
    
  </script>
</body>

</html>

Upvotes: 1

Related Questions