Skip to content

Instantly share code, notes, and snippets.

@alykat
Created April 1, 2016 21:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alykat/5fabb42475a6111ccc38591bac09550a to your computer and use it in GitHub Desktop.
Save alykat/5fabb42475a6111ccc38591bac09550a to your computer and use it in GitHub Desktop.
D3: Wrap label text and make SVG taller
/*
* Wrap a block of text to a given width
* via http://bl.ocks.org/mbostock/7555321
*/
var wrapText = function(texts, width, lineHeight) {
texts.each(function() {
var text = d3.select(this);
var words = text.text().split(/\s+/).reverse();
var word = null;
var line = [];
var lineNumber = 0;
var x = text.attr('x');
var y = text.attr('y');
var dx = parseFloat(text.attr('dx'));
var dy = parseFloat(text.attr('dy'));
var tspan = text.text(null)
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dx', dx + 'px')
.attr('dy', dy + 'px');
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(' '));
line = [word];
lineNumber += 1;
tspan = text.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dx', dx + 'px')
.attr('dy', lineNumber * lineHeight)
.attr('text-anchor', 'begin')
.text(word);
}
}
var bbox = text.node().getBBox();
if ((bbox.y + bbox.height) > (chartHeight + margins['bottom'])) {
chartHeight = (bbox.y + bbox.height) - margins['bottom'];
d3.select('svg')
.attr('height', chartHeight + margins['top'] + margins['bottom']);
}
});
}
/*
* Render values to chart.
*/
var values = d3.select('svg').append('g')
.attr('class', 'value');
values.append('text')
.html(chartData['label'])
.classed('label', true)
.attr('x', xScale(chartData['label']))
.attr('y', 25)
.attr('dx', 0)
.attr('dy', 0)
.call(wrapText, 80, 13);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment