Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 curved labels in the center of arc

I've been able to construct labeled donut chart just like in the following fiddle:

http://jsfiddle.net/MX7JC/9/

But now I'm trying to place the label in the middle of each arc and to span them along the arc (curve the label to follow each arc). To do that I've been thinking of putting the svg:text along svg:textPath using the d3.svg.line.radial function.

Then I stumbled upon the following fiddle:

http://jsfiddle.net/Wexcode/CrDUy/

However I'm having difficulty to tie the var arcs (the one having actual data) from the former fiddle with the var line from the latter fiddle as the latter fiddle uses the d3.range function as the data.

I've been doing trial-and-error for hours but nothing works. Does anyone know how the d3.svg.line.radial works together with the d3.svg.arc?

like image 576
Agustinus Verdy Avatar asked Jan 23 '26 22:01

Agustinus Verdy


1 Answers

I thought of a different approach. It's slightly roundabout way to do it, but requires a lot less custom code.

Instead of creating a custom line interpolator to draw the arc, use a d3 arc generator to create the curve definition for an entire pie segment, and then use regular expressions to extract the curve definition for just the outside curve of the pie.

Simplified example here: http://jsfiddle.net/4VnHn/10/

Example with the donut chart here: http://jsfiddle.net/MX7JC/691/

Key code:

var textArc = d3.svg.arc().outerRadius(r-45); //to generate the arcs for the text

textCurves.attr("d",  function(d) {
    var pie = textArc(d); //get the path code for the entire pie piece

    var justArc = /[Mm][\d\.\-e,\s]+[Aa][\d\.\-e,\s]+/; 
        //regex that matches a move statement followed by an arc statement

    return justArc.exec(pie)[0]; 
        //execute regular expression and extract matched part of string
});

The r-45 is just halfway between the inner and outer radii of the donuts. The [\d\.\-e,\s]+ part of the regular expression matches digits, periods, negative signs, exponent indicators ('e'), commas or whitespace, but not any of the other letters which signify a different type of path command. I think the rest is pretty self-explanatory.

like image 184
AmeliaBR Avatar answered Jan 25 '26 12:01

AmeliaBR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!