ltsimpso
ltsimpso

Reputation: 103

Drawing a Discrete number of rects in an svg element.using D3.js

js and I am trying to figure out how to draw a discrete number of rectangles in an SVG element. It could be 5 rectangles to a million. What is the best way to go about this? Should I be using the Ordinal scale since I have a discrete number of rectangles or should I be using the linear scale? So I'm thinking that the width of the rectangles should shrink as the number of rectangles grows larger.

Upvotes: 1

Views: 807

Answers (1)

Pablo Navarro
Pablo Navarro

Reputation: 8264

You have to compute the layout and create the appropriate scales. For example:

var width = 300,
    height = 20,
    margin = 2,
    nRect = 20,
    rectWidth = (width - (nRect - 1) * margin) / nRect,
    svg = d3.select('#chart').append('svg')
       .attr('width', width)
       .attr('height', height);

var data = d3.range(nRect),
    posScale = d3.scale.linear()
        .domain(d3.extent(data))
        .range([0, width - rectWidth]);

svg.selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('x', posScale)
    .attr('width', rectWidth)
    .attr('height', height);

I wrote a small jsfiddle with this code: http://jsfiddle.net/pnavarrc/CA7rY/

Upvotes: 1

Related Questions