简体   繁体   中英

Rotate SVG text around a circle then around itself using d3

I have a visual where the labels are placed by being rotated around the center of the circle. However this means that all labels on the left hand side of the circle are upside down. Is it possible to rotate the labels on the left hand side around themselves, after this rotation has taken place?

The visualisation is based on the zoomable sunburst from the d3js.org

The relevant code is:

function computeTextRotation(d) {
    var angle=(d.x +d.dx/2)*180/Math.PI - 90;
    return angle;
}

var texts = svg.selectAll("text")
        .data(partitioned_data)
        .enter().append("text")
        .filter(filter_min_arc_size_text)       
        .attr("transform", function(d) {return "rotate(" + computeTextRotation(d) + ")"})
        .attr("x", function(d) { return radius / 3 * d.depth; })    
        .attr("dx", "6") // margin
        .attr("dy", ".35em") // vertical-align  
        .text(function(d,i) {return d.name})

I tried the code below since I know this is possible if you know the x and y coordinates of the text, but it won't let me pass in dx and dy as the coordinates.

var texts = svg.selectAll("text")
        .data(partitioned_data)
        .enter().append("text")
        .filter(filter_min_arc_size_text)       
        .attr("transform", function(d) {
            if (computeTextRotation(d)>90&&computeTextRotation(d)<270) {
                return "rotate(" + computeTextRotation(d) + ") rotate(d.x,d.y,180)";
            } else {
                return "rotate(" + computeTextRotation(d) + ")";
            }})
        .attr("x", function(d) { return radius / 3 * d.depth; })    
        .attr("dx", "6") // margin
        .attr("dy", ".35em") // vertical-align  
        .text(function(d,i) {return d.name})

I am not 100% sure what you mean when you say "it wont let me pass dx and dy as the coordinates," but it looks like you are trying to pass in the variable names as strings instead of the variable values . In the code below I changed your .attr("tranform") to pass the values of dx and dy

var texts = svg.selectAll("text")
    .data(partitioned_data)
    .enter()
    .append("text")
    .filter(filter_min_arc_size_text)       
    .attr("transform", function(d) {
        if (computeTextRotation(d)>90&&computeTextRotation(d)<270) {
            return "rotate(" + computeTextRotation(d) + 
                   ") rotate(" + d.x + "," + d.y + ",180)";
        } else {
            return "rotate(" + computeTextRotation(d) + ")";
        }
    })
    .attr("x", function(d) { return radius / 3 * d.depth; })    
    .attr("dx", "6") // margin
    .attr("dy", ".35em") // vertical-align  
    .text(function(d,i) {return d.name})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM