Dot Plot in D3.js

倖福魔咒の 提交于 2019-12-06 08:07:36

问题


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:


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.



来源:https://stackoverflow.com/questions/25186636/dot-plot-in-d3-js

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