弧外标签(饼图)d3.js [英] Label outside arc (Pie chart) d3.js

查看:38
本文介绍了弧外标签(饼图)d3.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 d3.js 的新手,我正在尝试用它制作饼图.我只有一个问题:我无法将标签移出弧线...标签用 arc.centroid

I'm new to d3.js and I"m trying to make a Pie-chart with it. I have only one problem: I can't get my labels outside my arcs... The labels are positioned with arc.centroid

arcs.append("svg:text")
    .attr("transform", function(d) {
        return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")

谁能帮我解决这个问题?

Who can help me with this?

推荐答案

我可以解决这个问题 - 用三角学:).

I can solve that problem - with trigonometry :).

见小提琴:http://jsfiddle.net/nrabinowitz/GQDUS/

基本上,调用 arc.centroid(d) 会返回一个 [x,y] 数组.您可以使用勾股定理来计算斜边,即从饼图中心到圆弧质心的线的长度.然后您可以使用计算 x/h * desiredLabelRadiusy/h * desiredLabelRadius 来计算您的标签锚点所需的 x,y:

Basically, calling arc.centroid(d) returns an [x,y] array. You can use the Pythagorean Theorem to calculate the hypotenuse, which is the length of the line from the center of the pie to the arc centroid. Then you can use the calculations x/h * desiredLabelRadius and y/h * desiredLabelRadius to calculate the desired x,y for your label anchor:

.attr("transform", function(d) {
    var c = arc.centroid(d),
        x = c[0],
        y = c[1],
        // pythagorean theorem for hypotenuse
        h = Math.sqrt(x*x + y*y);
    return "translate(" + (x/h * labelr) +  ',' +
       (y/h * labelr) +  ")"; 
})

这里唯一的缺点是 text-anchor: middle 不再是一个很好的选择 - 你最好根据哪个来设置 text-anchor我们正在做的馅饼的一面:

The only downside here is that text-anchor: middle isn't a great choice anymore - you'd be better off setting the text-anchor based on which side of the pie we're on:

.attr("text-anchor", function(d) {
    // are we past the center?
    return (d.endAngle + d.startAngle)/2 > Math.PI ?
        "end" : "start";
})

这篇关于弧外标签(饼图)d3.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆