我有一个序号scale
,其中包含不同值的某些标签。我想显示该刻度的轴,其中轴标签与刻度标签不同。我有这段代码:
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正试图在每个tick值上调用scale;也就是说,它正在调用y("This is long")
,这导致NaN,因为“这很长”不在比例范围内。我不知道为什么会这样做。
Here is a fiddle显示问题。如果您注释掉.tickValues
行,则轴标签会正确显示。如果取消注释该行,则标签不起作用。
在d3中为顺序轴设置刻度标签的方法是什么?
答案 0 :(得分:18)
在摆弄了一点之后,我找到了答案。现在看来你必须使用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变得清晰。看起来格式化程序从一个标尺中取一个值作为输入,并且应该返回该值的显示版本。但是,对于序数尺度,该值可能不是数字,而是规模上的命名值。