2014-11-02 125 views
2

新手問題:如何將x軸刻度標籤從x軸移開?下面的代碼片段會產生這樣的:如何在d3.js中遠離x軸移動數字標籤?

current

而我要的是更多這樣的:

desired

從問題在這裏:

d3.js: Align text labels between ticks on the axis

它似乎我需要使用01選擇包含這些標籤的文本,然後給它們應用一些類似translate(0,-10)的東西,但我無法弄清楚這個文本「生活」的位置/執行這種選擇的語法。對不起,如果這很簡單,我對D3(和javascript)很新。誰能幫忙?提前致謝!代碼如下。

<script> 

var superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹", 
    formatPower = function(d) { return (d + "").split("").map(function(c) { return superscript[c]; }).join("");\ 
}; 

var margin = {top: 20, right: 20, bottom: 100, left: 100}, 
    width = 400, 
    height = 400; 

var x = d3.scale.log() 
    .domain([1e1, 1e4]) 
    .range([0, width]) 
    .nice(); 

var xAxis = d3.svg.axis() 
    .scale(x) 
    .orient("bottom") 
    .tickValues([1e1, 1e2, 1e3, 1e4]) 
    .ticks(0, function(d) { return 10 + formatPower(Math.round(Math.log(d)/Math.LN10)); }); 

var svg = d3.select("body").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 + ")"); 

svg.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + height + ")") 
    .call(xAxis) 
    .append("text") 
    .attr("class", "label") 
    .attr("x", (width+margin.left)/2) 
    .attr("y", 60) 
    .style("text-anchor", "end") 
    .text("x-axis label"); 

</script> 
+0

元素通過呼叫加入到'xAxis',所以你需要像'd3.select文本( 「g.x.axis」)全選( 「文本」)'。 – 2014-11-02 15:46:31

+0

感謝---這些評論非常有幫助! – user1071516 2014-11-02 16:25:41

回答

7

有一種更簡單的方法可以使用tickPadding來做到這一點。您在哪裏定義xAxis,只需添加.tickPadding(15)(將15更改爲所需的像素數)。

這裏舉例:http://jsfiddle.net/henbox/5q4k2r0p/1/

+0

謝謝,亨利S ---工作完美!我希望在發佈之前查看文檔時看到了這一點,但不知何故,我錯過了它。 – user1071516 2014-11-02 16:24:45