I inherited some bubblechart code to which I need to add text wrapping of the bubble chart labels.
How do I apply the answer here How to linebreak an svg text within javascript? to this scenario? I don't understand how to make d3 change the svg markup as given in the solution.
Here is my code:
function renderBubbles(root) {
var diameter = element[0].offsetWidth * .6,
format = d3.format(",d"),
color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var svg = d3.select(element[0]).append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function (d) {
return !d.children;
}))
.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
})
.on('mouseover', function (d) {
var nodeSelection = d3.select(this).style({opacity: '0.5'});
})
.on('mouseout', function (d) {
var nodeSelection = d3.select(this).style({opacity: '1'});
})
.on("click", function (d) {
$log.debug(d);
})
node.append("title")
.text(function (d) {
return d.className + ": " + format(d.value);
});
node.append("circle")
.attr("r", function (d) {
return d.r;
})
.style("fill", function (d) {
return color(d.packageName);
})
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function (d) {
return d.className.substring(0, d.r / 3);
});
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function (child) {
recurse(node.name, child);
});
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
}
d3.select(self.frameElement).style("height", diameter + "px");
Here is the solution given:
<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
<text x="0" y="0">
<tspan x="0" dy="1.2em">very long text</tspan>
<tspan x="0" dy="1.2em">I would like to linebreak</tspan>
</text>
</g>
Give this one a try. This was a solution of Lars, it's not from myself. But it works great in my project:
@Mark thank you.