2016-04-28 55 views
0

首先,直方圖不能正確縮放,我知道這與dx值有關,但無法弄清楚。其次,我想要將x軸的線性()改爲log(log.base(2))。當我這樣做,我得到D3.js縮放和使用對數刻度

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" 

直播>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

回答

3

爲什麼NaN

你越來越NaN的原因,我們不能對數尺度的領域包括:0(日誌(0)爲-Infinity

這裏是例如日誌

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 

比例尺

我認爲你目前的規模是正確的,但不是你真正想要的嗎?你能給更多的描述嗎?

+0

只是爲了數學上正確,當x趨近於0時的log(x)是負無窮大,或者在javascript'negative_infinity'中。 –

+0

@GerardoFurtado謝謝,糾正。 –

+0

非常感謝你的解釋,我能夠包裝這個東西。 –