2013-11-15 50 views
4

我有一個序號scale,其中有不同值的某些標籤。我想爲該比例顯示一個軸,其中軸標籤與刻度標籤不同。我有這樣的代碼:給出與標尺名稱不同的d3序數軸標籤

var width = 1000 
var height = 600 
var margins = { 
left: 100, // 40 
right: 25, 
bottom: 50, 
top: 0 
} 

var y = d3.scale.ordinal().domain(["This", "That", "Other"]).rangePoints([margins.top, height-margins.bottom], 1); 

var svg = d3.select("#plot").append("svg").attr("width",width).attr("height",height) 

var yAxis = d3.svg.axis() 
    .scale(y) 
    .orient("left") 
    .tickValues(["This is long", "That is long", "Other is long"]) 

svg.append("g") 
    .attr("class", "axis") 
    .attr("transform", "translate(" + margins.left + ",0)") 
    .classed("yaxis", true) 
    .call(yAxis); 

這用來工作,但顯然出現了在D3中,導致它不再工作在過去幾個月的一些變化。 (This other question也表示我應該能夠以這種方式使用tickValues。)滴答標籤不出現。我得到的JavaScript控制檯的錯誤說:

Unexpected value translate(0,NaN) parsing transform attribute. @ http://d3js.org/d3.v3.js:596 

通過代碼跟蹤,看來D3試圖調用每個刻度值規模;即它叫y("This is long"),這導致NaN,因爲「這很長」並不是規模。我不知道它爲什麼這樣做。

Here is a fiddle顯示問題。如果註釋掉.tickValues一行,則軸標籤正確顯示。沒有註釋該行,標籤不起作用。

在d3中設置序號軸的刻度標籤的方法是什麼?

回答

17

擺弄了一會之後,我找到了答案。現在看來,您必須使用tickFormat函數來定義軸如何顯示其刻度。該解決方案是更換與此.tickValues行:

.tickFormat(function (d) { 
    var mapper = { 
    "This": "This is long", 
    "That": "That is long", 
    "Other": "Other is long" 
    } 
    return mapper[d] 
}) 

The documentation不明確這一點;它只是明確地討論「數字格式化程序」。它不會使「格式化程序」的API清晰。看起來格式化程序從一個尺度中獲取單個值作爲輸入,並且應該返回該值的顯示版本。然而,對於序數量表而言,該值可能不是一個數字,而是規模上的一個已命名的值。

+1

要明確一點,對於mapper來說,左邊是你的原始值,右邊是你想要的值。 – JLewkovich