Dot plot in D3.js

I'm interested in creating a Dot plot (one that has consecutive points for each data value), but what I've achieved so far is to create only one point for each value.

To be clearer, let's say that for an array, I want the first value to create 5 circles, for the second 4 circles, etc.

array1 = [5,4,2,0,3] 

      

Any ideas?

Part of my code:

var circle = chart.selectAll("g")
    .data(d)
    .enter()
    .append("g")
    .attr("transform", function(d) { return "translate(" + xScale(d.values) + ",0)"; });
circle.append("circle")
    .attr("cx", xScale.rangeBand()/2)
    .attr("cy", function(d) { return yScale(d.frequency); })
    .attr("r", 5);

      

+3


source to share


1 answer


You can use nested choices and d3.range()

for this. The idea is that for each number, you create a range of numbers starting at 0 and ending at one less than the specified number. This gives you one item per number.

The position of the circles will then be indexed by the total number of values ​​and the number of values ​​you just created and the number of circles per line.



chart.selectAll("g")
  .data(data)
  .enter()
  .append("g")
  .selectAll("circle")
  .data(function(d) { return d3.range(d); })
  .enter()
  .append("circle")
  .attr("cx", function(d, i, j) {
      return ((i + d3.sum(data.slice(0, j))) % numPerRow + 1) * 15;
  })
  .attr("cy", function(d, i, j) {
      return Math.floor((i + d3.sum(data.slice(0, j))) / numPerRow + 1) * 15;
  })
  .style("fill", function(d, i, j) { return colour(j); })
  .attr("r", 5);

      

Complete the demo here .

+3


source







All Articles