4

I want to write a function, that returns a tick label with two lines of text. As I can see, an svg text tag is used for text labels. Is there a way to add tspan there or something?

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
nextstopsun
  • 443
  • 7
  • 14
  • possible duplicate of [How do I include newlines in labels in D3 charts?](http://stackoverflow.com/questions/13241475/how-do-i-include-newlines-in-labels-in-d3-charts) – Lars Kotthoff Nov 18 '13 at 22:03

1 Answers1

5

You can access the elements created by the axis: Demo

d3.select('svg')
  .append('g')
  .attr('transform', 'translate(180, 10)')
  .call(xAxis)
  .selectAll('text') // `text` has already been created
  .selectAll('tspan')  
  .data(function (d) { return bytesToString(d); }) // Returns two vals
  .enter()
  .append('tspan')
  .attr('x', 0)
  .attr('dx', '-1em')
  .attr('dy', function (d, i) { return (2 * i - 1) + 'em'; })
  .text(String);

Also, you'll have to set .tickFormat to '' on the axis.

animuson
  • 53,861
  • 28
  • 137
  • 147
musically_ut
  • 34,028
  • 8
  • 94
  • 106
  • I guess technically you could abuse `.tickFormat` to return text that contains the right tags, although you might have to mess around with namespaces to make that work. – Lars Kotthoff Nov 18 '13 at 22:08
  • 1
    @LarsKotthoff I think the text returned by `tickFormat` is [consumed by `.text`](https://github.com/mbostock/d3/blob/master/src/svg/axis.js#L45), and it cannot be used directly to _inject_ tags as text labels (it'll escape them). – musically_ut Nov 18 '13 at 22:11