yelji
yelji

Reputation: 81

in d3js bar chart i want to have fixed bar width

http://bl.ocks.org/d3noob/8952219

I want to have bar size width to be fixed..

from above example i have changed the code from

 svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });

to

svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", 50)
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });

but the labels are not moving to proper place also bars are getting overlapped

Upvotes: 4

Views: 3033

Answers (2)

Mo Gauvin
Mo Gauvin

Reputation: 169

I was looking for a similar solution. What @JulCh gave as an answer did not work out of the box for me, but lead me in the right direction.

Try:

var x = d3.scale.ordinal()
          .range(d3.range(data.length).map(function (d) { return d * 50; }));

Where the inner d3.range creates an array containing the number of elements determined by data.length or some constant number (the number of bars you would like displayed).

Example: If data.length or some constant is 8 then [0,1,2,3,4,5,6,7] is returned from d3.range(8)

The map function then multiplies your fixed width of 50 against each element in the array returning [0,50,100,150,200,250,300,350].

D3 will then use these exact values to place your bars.

Upvotes: 0

JulCh
JulCh

Reputation: 2888

You have to change the range() of your x scale, to fit with your bar width value:

var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);

to (if you want 50px as bar width)

var x = d3.scale.ordinal().range([0, data.length * 50]);

The range() method is used to define the display space for your scale.

Upvotes: 4

Related Questions