D3Js圆环图,避免标签文字叠加

时间:2015-02-09 09:47:32

标签: javascript d3.js charts highcharts donut-chart

在我的项目中,我有大量不同的图表,所有内容都使用D3J处理。其中一个图表应该是带有标签的甜甜圈类型。因此,基于此tutorial,我创建了此图D3Js Donut Chart。正如您所看到的那样(取决于数据)标签文字会叠加。

我的问题是,根据here中的高级图表,有任何方法可以像下面的示例一样:HighChart Donut Chart

感谢。

1 个答案:

答案 0 :(得分:0)

我认为有一个解决方案可以解决标签重叠的问题,当你在Solving D3 Label Placement with Constraint Relaxing打电话给标签时使用约束放松。

我快速浏览了这里的标签,似乎有效。这是我修改过的代码段:

alpha = 0.5;
spacing = 5;

function relax() {
again = false;
text.each(function (d, i) {
    a = this;
    da = d3.select(a);
    y1 = da.attr("y");
    text.each(function (d, j) {
        b = this;
        // a & b are the same element and don't collide.
        if (a == b) return;
        db = d3.select(b);
        // a & b are on opposite sides of the chart and
        // don't collide
        if (da.attr("text-anchor") != db.attr("text-anchor")) return;
        // Now let's calculate the distance between
        // these elements. 
        y2 = db.attr("y");
        deltaY = y1 - y2;

        // If spacing is greater than our specified spacing,
        // they don't collide.
        if (Math.abs(deltaY) > spacing) return;

        // If the labels collide, we'll push each 
        // of the two labels up and down a little bit.
        again = true;
        sign = deltaY > 0 ? 1 : -1;
        adjust = sign * alpha;
        da.attr("y",+y1 + adjust);
        db.attr("y",+y2 - adjust);   
    });

});

if(again) {
    setTimeout(relax,20)
}
}

relax();

fiddle

只需按照上面链接的教程中的下一步操作,即可更新折线以跟踪标签到新位置。祝你好运!