How to make tick axis labels hyperlinks in D3.js

In D3.js, how to assign HTML elements / attribute labels to labels? I'm particularly interested in creating their hyperlinks, but it can be generalized to make them images or something weird, like alternating div classes.

var data = [{"count": 3125,"name": "aaa"}, {"count": 3004,"name": "bbb"}... y = d3.scale.ordinal() .rangeRoundBands([0, height], 0.1) .domain(data.map(function (d) { return d.name; })) yAxis = d3.svg.axis().scale(y) vis.append("g") .attr("class", "y axis") .call(yAxis) 

http://jsfiddle.net/SFDrv/

So, in JSfiddle, how can I link to www.example.com/aaa, www.example.com/bbb, www.example.com/ccc, etc.?

+1
source share
2 answers

For a published JSfiddle, you can create a selection from all text , which are strings (these are y-axis ticks), and then use .on("click", function) to link each label. Here is a working example:

 d3.selectAll("text") .filter(function(d){ return typeof(d) == "string"; }) .style("cursor", "pointer") .on("click", function(d){ document.location.href = "http://www.example.com/" + d; }); 

I forked your JSFiddle and found the whole example there: http://jsfiddle.net/mdml/Qm9U7/ .

A better solution would be to have an array of Y axis values ​​and use them to filter the text elements in the document, instead of checking if each data element is a text string. However, the best way to do this depends on the rest of the code, so it may differ from application to application.

+3
source

To create an axis with images, you need to create them yourself, and not use d3.svg.axis() . This creates floating li tags with a specific width ...

 // generate axis x = d3.scale.linear().range([min, max]).domain([minValue, maxScaleValue]); xAxis = d3.scale.identity().domain([minValue, maxScaleValue]); var ticks = xAxis.ticks(10); if (ticks.length) { var tickDiff = Math.abs(ticks[1] - ticks[0]); scope.legend .selectAll('li') .data(ticks) .enter() .append('li') .text(xAxis) .style('width', x(tickDiff)); } scope.legend .selectAll("li") .data(ticks) .exit() .remove(); 

There is also a useful article on the d3 axis , which helped me a lot.

0
source

All Articles