Refuse HTML on X-Axis Ticks

I would like to display HTML on the x-axis of my D3 graph. Basically, I want each label on the axis to be a hyperlink to another column from the data.

I tried

x.domain(data.map(function(d) { return "<a href=\"" + d.SiteUrl + "\">" + d.Name + "</a>"; })); 

but it does not work at all. Instead of getting a hyperlink, I get the actual text value:

 <a href="http://example.com">Something</a> 

I also tried adding

 .tickFormat(function(d) { return "<a href=\"" + d.SiteUrl + "\">" + d.Name + "</a>"; }) 

on the x axis, and also changing the value of .attr("x", ...) to

 .attr("x", function(d) { return "<a href=\"" + d.SiteUrl + "\">" + x(d.Name) + "</a>"; }) 

on the chart itself.

Did I miss something?

+6
source share
1 answer

(Based on https://groups.google.com/d/msg/d3-js/zoUjrm75iCg/EJg0YhnTw3YJ )

The trick is to use svg:foreignObject (as pointed out by @thatOneGuy in the comments), then you can put any HTML inside the axis label. The at html function below gets the passed data[i].name , where you can place arbitrary HTML.

 var height = 500; var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .tickSize(0).tickPadding(0).tickFormat(function(d) {return '';}); var tx = -5; var ty = 2; var tw = 50; var th = 10; chart.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("g") .append("svg:foreignObject") .attr("width",tw) .attr("height",th) .attr("x", tx) .attr("y", ty) .append("xhtml:div") .attr("class", "my-x-axis-label") .html(function(schema) {return schema;}); 

CSS

 div.my-x-axis-label { font: 10px sans-serif; } 
+3
source

All Articles