Eni*_*aRM 14 javascript axis-labels d3.js
我的x轴目前有编号的刻度.我希望将ticks替换为来自我对象的数据(特别是关键字值).我怎么做到这一点?
var dataset = [
{"keyword": "payday loans", "global": 1400000, "local": 673000, "cpc": "14.11"},
{"keyword": "title loans", "global": 165000, "local": 160000, "cpc": "12.53" },
{"keyword": "personal loans", "global": 550000, "local": 301000, "cpc": "6.14"},
{"keyword": "online personal loans", "global": 15400, "local": 12900, "cpc": "5.84"},
{"keyword": "online title loans", "global": 111600, "local": 11500, "cpc": "11.74"}
];
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
// xAxis
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + (h) + ")")
.call(xAxis);
//xAxis Label
svg.append("text")
.attr("transform", "translate(" + (w / 2) + " ," + (h + margin.bottom - 5) +")")
.style("text-anchor", "middle")
.text("Keyword");
Run Code Online (Sandbox Code Playgroud)
Lar*_*off 37
实现此目的的最简单方法是tickFormat为轴设置功能:
var xAxis = d3.svg.axis()
.scale(xScale)
.tickFormat(function(d) { return dataset[d].keyword; })
.orient("bottom");
Run Code Online (Sandbox Code Playgroud)
您可能需要稍微调整宽度以适合标签(或旋转它们).
执行此操作的"正确"方法是将域值指定xScale为关键字而不是数组索引.然后你必须改变所有其他使用的代码xScale.