2

Using d3, I am trying to write a script to visualize the size of a number by showing it composed of individual blocks . So the number 5 would be composed of 5 rectangle. The general syntax to create rectangles within the svg is something as follows.

var p = d3.select("body").selectAll("p")
    .data([5, 3, 10])
    .enter()
    .append("rect) 
    ...

However, what I really want is something that append multiple rectangles per data element.

var p = d3.select("body").selectAll("p")
    .data([5, 3, 10])
    .enter()
    .do(CreatedRectangles(d))

Anyone know how to do this easily?

1 Answer 1

5

You can use a nested selection and d3.range() for this:

d3.select("body")
  .selectAll("p")
  .data([5,3,10])
  .enter()
  .append("p")
  .selectAll("p")
  .data(function(d) { return d3.range(d); })
  .enter()
  .append("p")
  .html(String);

Demo here.

You can use your .do() as well, except that it's called .each(). CreateRectangle() would look something like this.

function CreateRectangle(d) {
  d3.select(this).selectAll("p").data(d3.range(d)).enter().append("p").html(String);
}

It works similarly with SVG and rect elements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.