Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap D3 labels with ticks

I am trying to get my labels to wrap correctly. I need to get the ticks and labels to match up. I am using a wrap function for the labels but could not get it to work with the tspans.

SCREENSHOT

WORKING DEMO

UPDATE

Here is before and after picture to help understand what Im after.

BEFORE AFTER

like image 670
texas697 Avatar asked Nov 06 '22 02:11

texas697


1 Answers

Sadly there is no simple way to get SVG <text> elements' content to wrap like it would in HTML. However I did find this answer to a similar question which suggests using the D3 Plus library to add text wrapping to D3.

If for some reason that isn't an option you will probably have to calculate the wrapping yourself, it is a bit of a nasty process but is doable with some effort. In general terms you need to:

  1. Create an HTML element with the same width and font styles as the target SVG text
  2. Add the desired content to this element word-by-word
  3. After adding each word check the height of the HTML element, if it has increased you know you need a newline before that word
  4. Once you know how many lines it needs use <tSpan> elements to output each line of text (you'll have to manually set the top offset for each new line)

I'd definitely advise using the library though if at all possible!

like image 115
SimonR Avatar answered Nov 12 '22 14:11

SimonR