view raw
EnigmaRM EnigmaRM - 9 months ago 37
Javascript Question

d3.js Specify text for x-axis

My x-axis currently has numbered ticks. I want the ticks to be replaced with data from my object (specifically the keyword value). How would I accomplish this?

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()
// xAxis
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + (h) + ")")
//xAxis Label
.attr("transform", "translate(" + (w / 2) + " ," + (h + margin.bottom - 5) +")")
.style("text-anchor", "middle")


The easiest way to achieve this is to set the tickFormat function for your axis:

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

You might have to tweak the width a bit to fit the labels (or rotate them).

The "proper" way to do this would be to specify the domain values for you xScale as the keywords instead of the array indices. Then you would have to change all the other code that uses xScale as well though.