D3.js缩放和使用对数刻度

时间:2016-04-28 03:48:38

标签: javascript d3.js

首先直方图没有正确缩放,我知道它与dx值有关,但是无法弄清楚。其次,我想将x的轴从linear()更改为log(log.base(2))。当我这样做时,我得到了

 d3.v3.min.js:1 Error: Invalid value for <rect> attribute x="NaN"
 d3.v3.min.js:1 Error: Invalid value for <rect> attribute width="NaN" 
 d3.v3.min.js:1 Error: Invalid value for <text> attribute y="NaN" 
 d3.v3.min.js:1 Error: Invalid value for <text> attribute dx="NaN"

活&GT; https://jsfiddle.net/akhiforu/3pnp4tne/1/

var t2 = [20215,16103,45455,14985,256670,13188,15328,49491,63460,34423,56615,16392,516284,88574,27766,43698,44305,101564,4481,101759,9127,51829,37063,18836,23825,5917,20652,84395,26395,168068,20444,118011,16853,19410,28493,80160,135780,41298,15050,4522,956406,45379,37417,35563,182006,87470,7335,40958,43437,70482,13675,195163,17662,161188,14333,63379,16437,41579,115290,86759,20540,29509,30362,21398,103527,15694,133251,395118,52066,24178,169511,73608];
 var w = 700;
    var h = 500;
    var p = 50;
    var thresholds = [0,20000,40000,60000,80000,100000,1000000];
    var hpop = [];

    htemp = t2;
    hpop = htemp.sort(function(a, b) {
        return a - b;
    });

    console.log(hpop);

    var hdata = d3.layout.histogram()
    .bins(thresholds)
    (hpop)
    console.log(hdata);

    var y = d3.scale.linear()
        .domain([0, d3.max(hdata.map(function(i){return i.length;}))])
        .range([0, h]);

    var x = d3.scale.linear()
        .domain([0,d3.max(hpop)])
        .range([0, w]);

    console.log(d3.max(hpop));

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(d3.format("s"));

    var histo = d3.select("#hist").append("svg")
        .attr("width", w)
        .attr("height", h + p)
        .append("g")
        .attr("transform", "translate(20,0)");

    histo.append("g")
        .attr("transform", "translate(0," + h + ")")
        .attr ("class", "axis")
        .call(xAxis);

    var hbar = histo.selectAll(".hbar")
        .data(hdata)
        .enter()
        .append("g");

    hbar.append("rect")
        .attr("x", function(d){return x(d.x);})
        .attr("y",function(d){return h - y(d.y);})
        .attr("width", function(d){return x(d.dx);})
        .attr("height", function(d){return y(d.y);})
        .attr("fill", "blue");

    hbar.append("text")
        .attr("x", function(d){return x(d.x);})
        .attr("y",function(d){return h - y(d.y);})
        .attr("dy", "20px")
        .attr("dx", function(d){return x(d.dx)/2;})
        .attr("fill", "#fff")
        .attr("text-anchor", "middle")
        .text(function(d){return d.y;});

谁能告诉我这是什么问题..?

更新:感谢您快速的头脑风暴我用新秤重写了代码。 enter image description here

1 个答案:

答案 0 :(得分:3)

为什么NaN

您收到NaN的原因我们无法在日志范围内包含0(log(0)为-Infinity

以下是log

的示例
var x = d3.scale.log ()
    .domain([2, 8])
    .range([0, 100])
    .base(2)


console.log(x(2)) => 0
console.log(x(4)) => 50
console.log(x(8)) => 100

<强>比例

我认为你目前的规模是正确的,但不是你真正想要的吗?你能给出更多描述吗?