我想做一个水平气泡图,但我不知道如何避免气泡之间的碰撞。每个气泡代表一个年份,可以有任意的数值和大小,而不会发生碰撞。我怎么才能解决这个问题?
D3版本
<script src="https://unpkg.com/[email protected]/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;
});
你可以堆叠气泡,但不说它们的具体位置,而是有条件地将它们定位到前一个气泡上。
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 }
})
你可以使用 cx和 半径 价值观 现状 在于
.attr("cx", function(d, i) {
return d.cx;
})
.attr("cy", function() {
return 100;
})
.attr("r", function(d) {
return d.radius;
})
另外,别忘了相应地修改文本的位置,并将var data(而不是const)改为