官术网_书友最值得收藏!

Adding text legends

To add the text legends, we only need a couple of lines of JavaScript:

var textElements = pieContainer.selectAll(".labels").data(arcs); 
textElements.enter()
.append("text")
.attr("class", "labels")
.merge(textElements)
.text( function(d) { return d.data.yearsInBusinessLabel + " (" + d.data.count + ")" })
.attr("dy", "0.35em" )
.transition()
.ease(d3.easeCircle)
.duration(2000)
.attrTween("transform", tweenLabels)
.styleTween("text-anchor", tweenAnchor);

Here, we use the standard D3 approach of selecting elements, binding data (arcs, which are the result of the d3.pie() function call), and adding or updating elements. For the labels we add a text element, and use the text() function to set the label based on the input data. Remember, the original data that we passed into the d3.pie() function to generate the arcs array can be accessed through the data property. To position the labels, we once again use a transition with the same properties as the one we used for the donut segments. This time, however, we use the attrTween function on the transform attribute to position the labels. We also use a styleTween function for the text-anchor style. The text-anchor style is used to determine whether the text is anchored to the start, the middle, or the end of its position. We use this to make sure the text-anchor property is set to start for the text labels on the right side of the donut, and to end for the ones on the left side. The interpolators used for this are shown here:

var labelsArc = d3.arc() 
.outerRadius(height/2 * 0.7)
.innerRadius(height/2 * 0.7);

function tweenLabels(d) {
var interpolator = getArcInterpolator(this, d);
return function (t) {
var p = labelsArc.centroid(interpolator(t));
var xy = p
xy[0]= xy[0] * 1.2
return "translate(" + xy + ")";
};
}

function tweenAnchor(d) {
var interpolator = getArcInterpolator(this, d);
return function (t) {
var x = labelsArc.centroid(interpolator(t))[0];
return (x > 0) ? "start" : "end";
};
}

As you can see, this looks very similar to the interpolator we used for the donut segments. The main change is that we use a different arc function. We use the labelsArc function to positon the text at the center of an invisible donut that is a bit larger than defined for the normal donut. We position the text at the center of each invisible donut segment using the centroid function to determine that position. For the text-anchor style, we just check whether we're on the right or left side of the donut, and either return start or end. With this code in place, we get animated text labels that move together with the donut segments:

Now all that is left to do is add the lines pointing from the center of each donut segment to the start of the text elements.

主站蜘蛛池模板: 仁寿县| 当阳市| 虹口区| 安多县| 沂源县| 历史| 北碚区| 清苑县| 甘孜县| 调兵山市| 青河县| 高唐县| 晋宁县| 宁晋县| 垦利县| 临湘市| 恩施市| 特克斯县| 嘉祥县| 三亚市| 朝阳市| 广水市| 许昌县| 理塘县| 贺州市| 海原县| 特克斯县| 靖边县| 迁安市| 绥中县| 沙雅县| 津南区| 南投市| 嘉黎县| 华蓥市| 石门县| 昌黎县| 新田县| 阿鲁科尔沁旗| 通榆县| 怀柔区|