d3.js中的简单条形图

时间:2014-05-10 14:38:57

标签: javascript json d3.js

我试图根据this example创建一个简单的条形图 这是我的代码和json文件: 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"}
]

由于某种原因xLPU.rangeBand()返回无穷大,有人能解释我的错误吗?

1 个答案:

答案 0 :(得分:1)

对于序数比例,您需要在设置域名后调用.rangeBands()(或.rangeRoundBands())。当您调用此函数时,根据域中的元素划分给定范围 - 如果域尚未设置,则只有一个频段覆盖,如您所知,无穷大。