سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top