Dot Plot in D3.js

2020-07-22 16:57发布

I'm interested in creating a Dot plot (the one with the consecutive dots for every data value) but what I've managed so far is to create just a single dot for every value.

To be more clear, let's say for the array1 I want for the first value to create 5 circles, for the second 4 circles and so on...

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

1条回答
家丑人穷心不美
2楼-- · 2020-07-22 17:03

You can use nested selections and d3.range() for this. The idea is that for each number, you generate a range of numbers starting at 0 and stopping at one less than the number given. This gives you one element per number.

The position of the circles would then be determined by the indices into the total number of values and the number of values you've just generated and the number of circles per row.

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 demo here.

查看更多
登录 后发表回答