D3.js“饼图标签"重叠 [英] D3.js 'Pie Charts Labels' Overlapping

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

问题描述

StackOverflow社区.我试图找到我遇到的问题的解决方案,但无法获得任何帮助.我能找到的最接近的东西是,似乎没有解决方案.我是D3.js的完整入门者,所以这也可能就是为什么我无法解决这种情况.我也尝试过浏览文档,但没有成功.所以这是我的问题.我试图做一些数据可视化工作,却偶然发现D3.js中的饼图示例库,我认为这很漂亮.一旦我开始将大量的值添加到图形中,尽管我发现我在重叠标签方面遇到了问题,如下所示.我只是更改了示例页面中的代码以使其成功,因此我可以创建多个图表.除此之外,它基本上是相同的.感谢您提供任何帮助或信息!

Hi StackOverflow community. I tried to find the solution for a problem I'm having and was unable to get anything helpful. The closest thing I could find was this which seems to not have a solution. I'm a complete beginner to D3.js so this may also be why I'm having trouble resolving the situation. I tried digging through the documentation as well with no success. So here's my problem. I was trying to do some data visualization stuff and stumbled upon this pie chart in the D3.js example library, which I thought was pretty nifty. Once I started putting a large amount of values into the graph though I noticed I had problems with overlapping labels as can be seen below. I've only altered the code from the example page to make it so I can create multiple charts. Besides that it's essentially the same. Thanks for any help or information anyone can provide!

重叠标签

推荐答案

这仅适用于d3 v4.想法是将每个节点与其余节点进行比较,并在检测到冲突时移动其位置.以下代码段将this.texts用作标签的d3选择.一旦检测到碰撞,该元素将被移至下方-可能无法针对特定情况进行优化.

This will work only for d3 v4. The idea is to compare each node with the rest and move its position if collision is detected. The following code snippet uses this.texts as d3 selection of the labels. Once a collision is detected the element will be moved below - might not be optimised for a specific case.

const nodes = this.texts.nodes();
  for (let i = 0; i < nodes.length; i++) {
    for (let j = i + 1; j < nodes.length; j++) {
      const previous = nodes[i];
      const elem = nodes[j];
      const thisbb = elem.getBoundingClientRect(),
        prevbb = previous.getBoundingClientRect();
      if (!(thisbb.right < prevbb.left ||
        thisbb.left > prevbb.right ||
        thisbb.bottom < prevbb.top ||
        thisbb.top > prevbb.bottom)) {
        const matrix = previous.transform.baseVal.consolidate().matrix;
        d3.select(elem).attr('transform', `translate(${matrix.e}, ${matrix.f + prevbb.bottom - prevbb.top})`);

      }
      const elemMatrix = elem.transform.baseVal.consolidate().matrix;
      pieData[j].pos = [elemMatrix.e, elemMatrix.f];
    }
  }

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

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