0

I'm trying to create a simple bar chart according to this example Here is my code and json file: statistics.html

var xLPU=d3.scale.ordinal()
.rangeBands([0, width]);
var yLPU=d3.scale.linear()
.range([height,0]);
var xLPUAxis = d3.svg.axis()
    .scale(xLPU)
    .orient("bottom");

var yLPUAxis = d3.svg.axis()
    .scale(yLPU)
    .orient("left");
var LPUdivision=d3.select("#LPU").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("LPUdivision.json",function(data){
    xLPU.domain(data.map(function(d){return d.lpu;}));
    yLPU.domain([0,d3.max(data, function(d) { return d.amount; })]);
    LPUdivision.append("g")
    .attr("class","x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xLPUAxis);
    LPUdivision.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    LPUdivision.selectAll(".bar")
    .data(data)
    .enter()
    .append("rect")
    .attr("class","bar")
    .attr("x",function(d){return xLPU(d.lpu)})
    .attr("width", x.rangeBand())
    .attr("y", function(d) { return yLPU(d.amount); })
    .attr("height", function(d) { return height - yLPU(d.amount); });

LPUdivision.json

[
{"lpu":"lpu1","amount":"20"},
{"lpu":"lpu2","amount":"40"},
{"lpu":"lpu3","amount":"80"},
{"lpu":"lpu4","amount":"10"},
{"lpu":"lpu5","amount":"5"},
{"lpu":"lpu6","amount":"6"}
]

For some reason xLPU.rangeBand() returns infinity, can anyone explain me what am I doing wrong?

4
  • 1
    You need to set .rangeBands() after setting the .domain(). Commented May 10, 2014 at 14:41
  • In case you might be interested, nvd3 has multiple bar charts using d3.js Commented May 10, 2014 at 14:56
  • Thanx to Lars Kotthof, works now, very strange that official example is wrong. Commented May 10, 2014 at 14:58
  • You can answer my question, I'll sure approve it. Commented May 10, 2014 at 15:00

1 Answer 1

1

For ordinal scales, you need to call .rangeBands() (or .rangeRoundBands()) after the domain has been set. When you call this function, the given range is divided according to the elements in the domain -- if the domain has not been set, there's only one band that covers, as you found out, infinity.

Not the answer you're looking for? Browse other questions tagged or ask your own question.