thgnuyen
thgnuyen

Reputation: 159

D3 Scatter Plot With Nested Array

I am trying to create a scatter plot using D3 but only two of the points show up.

My data has this format

  var data = [
      {
        key: "group1",
        x: [10,20],
        y: [10,30],
        label: ["point1", "point2"]
      },
      {
      {
        key: "group2",
        x: [5,10,25],
        y: [20,25,15],
        label: ["point3", "point4", "point5"]
      },
      },
     ]; 

The x and y go together, for example in "goup1" the points are (10,10) and (20,30) and in "goup2" the points are (5,20), (10,25), and (25,15). I want to draw all five points on the scatter plot.

And I am drawing the points with this

var scatterPlotCircles = this.scatterChartContainer.selectAll(".scatterPlotDots")
        .data(data)
        .enter().append("circle")
        .attr("class", "scatterPlotDots")
        .attr("cx",function(d,i){
            return scatterChartXScale(d.x[i]);
        })
        .attr("cy",function(d,i)
              {
                  return scatterChartYScale(d.y[i]);
              })
        .attr("r", 5)
        .attr("fill", function(d,i){ return color(d.key); })
        .style("opacity", 1);

I don't think that I am accessing the data correctly. Does anyone know how to correctly access the data to plot them on the graph?

The link to the jsfiddle. Thank you.

Upvotes: 0

Views: 1351

Answers (1)

Richard Poole
Richard Poole

Reputation: 3984

I find the easiest option is to restructure the data to match the intended SVG.

// restructure the data to make life easier
data = data.map(function(d) {
    return {
        key: d.key,
        points: d.label.map(function (l, i) {
            return {
                label: l,
                x: d.x[i],
                y: d.y[i]
            };
        })
    };
});

Then it's just a matter of creating a <g> container for each group.

var scatterPlotGroups = scatterChartContainer.selectAll(".scatterPlotGroup")
    .data(data)
    .enter().append("g")
    .attr("class", "scatterPlotGroup");

var scatterPlotCircles = scatterPlotGroups.selectAll("circle")
    .data(function(d) { return d.points; })
    .enter().append("circle")
    .attr("cx", function(d) { return scatterChartXScale(d.x); })
    .attr("cy", function(d) { return scatterChartYScale(d.y); })
    .attr("r", 5)
    .attr("fill", function() { return color(d3.select(this.parentNode).datum().key); });

Working JSFiddle here.

Upvotes: 1

Related Questions