【问题标题】:Avoid collision in Bubble chart避免气泡图中的碰撞
【发布时间】:2020-06-03 14:46:14
【问题描述】:

我正在尝试制作水平气泡图,但我不知道如何避免气泡之间的碰撞。每个气泡代表一年,可以有任何价值和大小而不会发生碰撞。我该如何解决这个问题?

D3 版本

<script src="https://unpkg.com/d3@5.15.0/dist/d3.min.js"></script>

Js

var width = 1000;
var height = 500;

const data = [ { name: "2010", value: 2 }, 
               { name: "2011", value: 20 }, 
               { name: "2012", value: 8 }, 
               { name: "2013", value: 2 }, 
               { name: "2014", value: 31 }, 
               { name: "2015", value: 45 }, 
               { name: "2016", value: 20 }, 
               { name: "2017", value: 10 },
               { name: "2018", value: 5 },
               { name: "2019", value: 6 },
               { name: "2020", value: 1 }];    

var svg = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

var g = svg.selectAll("g")
           .data(data)
           .enter()
           .append("g")
           .attr("transform", function(d, i) {
               return "translate(0,0)";
           });

g.append("circle")
  .attr("cx", function(d, i) {
      return (i * 100) + 50;
  })
  .attr("cy", function() {
      return 100;
  })
  .attr("r", function(d) {
      return d.value * 2;
  })
  .attr("fill", function(d, i) {
      return '#FF5532';
  });

g.append("text")
  .attr("x", function(d, i) {
      return (i * 100) + 50;
  })
  .attr("y", 105)
  .attr("stroke", "black")
  .attr("font-size", "12px")
  .attr("font-family", "sans-serif")
  .text(function(d) {
      return d.name;
  });

【问题讨论】:

    标签: javascript d3.js data-visualization


    【解决方案1】:

    您可以堆叠气泡,而无需说明它们的确切位置,而是有条件地将它们定位到前一个。

    var currentCx = 0
    const size_factor = 2
    
    data = data.map(yearData => {
    currentCx += yearData.value*size_factor
    const _currentCx = currentCx
    
    // This line is repeated, because the center of circle, 
    // Is exctracted in the middle of the two sums
    currentCx += yearData.value*size_factor
    const _radius = yearData.value*size_factor
    
    return {...yearData, cx: _currentCx, radius: _radius }
    })
    

    您可以在 attr 中使用 cxradiusas-is

    .attr("cx", function(d, i) {
      return d.cx;
    })
    .attr("cy", function() {
      return 100;
    })
    .attr("r", function(d) {
     return d.radius;
    })
    

    另外不要忘记相应地修改文本位置,并制作 var 数据(而不是 const)

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2014-07-03
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2017-11-03
      • 2019-11-27
      相关资源
      最近更新 更多