The 'd3-circle-text' plug-in works great on a static circle-pack (many thanks to musically-ut for contributing https://github.com/musically-ut/d3-circle-text). However, on a zoomable circle-pack, labels fly about the place (in the fiddle, they stay static not repositioning on zoom).
Is it possible to get the circle-text to zoom with the circles? (If the plug-in isn't zoomable, that's ok. I'll try another labelling approach.)
Here's the code section I'm working on:
////////////Circle text
var circleText = d3.circleText()
.radius(function(d) {
return d.r - 5;
})
.value(function(d) {
return d.key; //Get lables
})
.method('align')
.spacing('exact')
.precision(0.1)
.fontSize('100%');
var gTexts = svg.selectAll('g.label')
.data(pack.nodes) //Returns names
.enter()
.append('g')
.classed('label', true)
.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
/*.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; }); */ An attempt - not working
/*.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; }); */ An attempt - not working
//Only put on 'parent' circles
gTexts.filter(function(d) {
return !!d.children;
})
.call(circleText)
//.style('fill', 'white');
Here's a full fiddle: http://jsfiddle.net/cajmcmahon/9a5xaovv/1/
Thanks for any help.
I have updated the plugin at musically-ut/d3-circle-text
The the layout generation has been simplified and it now handles transitions correctly.
The updated fiddle: http://jsfiddle.net/nxmkoo95/
Notable changes
- Hoisted the definition of
circleText
to the top level and removed the call to.precision
. - Used a class
.leaf-label
to identify the text labels which had to be manually moved. - Added a call to update the radius function of
circleText
and moved theg.label
to the correct place.
function zoom(d, i) {
var k = r / d.r / 2;
x.domain([d.x - d.r, d.x + d.r]);
y.domain([d.y - d.r, d.y + d.r]);
var t = svg.transition()
.duration(d3.event.altKey ? 7500 : 750);
t.selectAll("circle")
.attr("cx", function(d) {
return x(d.x);
})
.attr("cy", function(d) {
return y(d.y);
})
.attr("r", function(d) {
return k * d.r;
});
circleText.radius(function (d) { return k * d.r - 5.0; });
t.selectAll('g.label')
.attr('transform', function (d) {
return "translate(" + x(d.x) + ',' + y(d.y) + ')';
})
.filter(function (d) { return !!d.children; })
.call(circleText);
t.selectAll(".leaf-label")
.attr("x", function(d) {
return x(d.x);
})
.attr("y", function(d) {
return y(d.y);
})
.style("opacity", function(d) { return k * d.r > 20 ? 1 : 0; });
node = d;
d3.event.stopPropagation();
}
来源:https://stackoverflow.com/questions/31073452/d3-circle-text-on-zoomable-circle-pack