Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML on X-Axis Ticks

I would like to render 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've tried

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

but it's not working, at all. Instead of getting a hyperlink I get the actual text value:

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

I've also tried adding

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

on the x-axis, as well as altering the .attr("x", ...) to

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

on the chart itself.

Am I missing something?

like image 511
Der Kommissar Avatar asked May 18 '16 09:05

Der Kommissar


1 Answers

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

The trick is to use svg:foreignObject (as stated by @thatOneGuy in the comments), then you can place any HTML inside the axis label. The function at html below gets passed data[i].name, where one 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;
}
like image 141
koppor Avatar answered Oct 16 '22 04:10

koppor