2013-04-23 216 views
13

我的x軸當前有編號的刻度。我希望用我的對象中的數據(特別是關鍵字值)替換蜱。我怎麼做到這一點?d3.js爲x軸指定文本

I have a working Fiddle

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"); 

回答

36

實現這一目標最簡單的方法是設置tickFormat功能,爲您的軸:

var xAxis = d3.svg.axis() 
    .scale(xScale) 
    .tickFormat(function(d) { return dataset[d].keyword; }) 
    .orient("bottom"); 

您可能需要調整的寬度有點適合標籤(或rotate them)。

完成此操作的「正確」方法是將xScale的域值指定爲關鍵字而不是數組索引。然後,您將不得不更改使用xScale的所有其他代碼。

+0

非常好。我曾嘗試類似的東西。但它一起打破了軸心。但它現在起作用了!謝謝。然後我添加了一些樣式來旋轉文本以防止重疊。 – EnigmaRM 2013-04-23 21:17:58