我正在尝试编写一个函数来选择该轴的最后一个刻度内的文本,并在其前面添加“$”(因此在本例中文本为 $100)
到目前为止,我已经使用此原型(prototype)来选择最后一个刻度:
d3.selection.prototype.last = function() {
var last = this.size() - 1;
return d3.select(this[0][last]);
};
//first I select all of the ticks:
var tickLabels = d3.selectAll("g.cardbasegroup g.yaxis g.tick");
//and then use that prototype to select the last one:
var lastTick = tickLabels.last();
...但是现在如何抓取该刻度内的文本并在前面加上“$”?
最佳答案
你可以这样做:
var textNode = lastTick.select('text');
textNode.text('$' + textNode.text());
另一种方法是使用 .tickFormat
方法。
var nbTicks = 5;
var axis = d3.svg.axis()
.ticks(nbTicks)
.tickFormat(function(d, i) {
if(i == nbTicks) {
return '$' + d;
}
return d;
});
此方法的问题在于,linear.ticks
(用于生成正确的刻度数)的文档告诉我们:
The specified count is only a hint; the scale may return more or fewer values depending on the input domain.
引用文献:
关于javascript - D3.JS 尝试格式化轴第一个刻度中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467519/