d3 Treemap Label Truncation

By | August 15, 2013

I received a comment asking how to truncate labels in my treemap example. Here is a quick example showing how I handled it on a recent project. I am sure there are other ways to do this and if anyone has a better alternative, please detail it in the comments. Basically, when using labels in D3, I find it easier to work with HTML DIVs rather than the SVG Text nodes. So, using the ForeignObject element within the SVG, I add a DIV containing the label and I can control the wrapping, truncation, etc using styling. Internet Explorer, as usual, is years behind the other modern browsers so you have to “speak slowly” when IE is detected and dumb things down a bit so it can keep up. I basically have a little function that determines the length of the label text and if it exceeds the width of the treemap rectangle, I truncate it manually. See the Gist for the code and see the demo below. (Keep in mind that I have not taken the time to deal with the parent group labels so you will see some over lap from those)
NOTE: The labels do not show up in IE10 even though they work in IE9. Big surprise. Maybe one day Microsoft will make a browser that works. I’m sure I could dig around and figure out why IE cannot handle these simple labels but until then, just pretend.

 

Leave a Reply

Your email address will not be published. Required fields are marked *