我在這里有一張基本地圖,帶有虛擬資料。基本上是一張氣泡圖。
問題是我有多個點(例如:20)具有完全相同的 GPS 坐標。下圖是我的帶有虛擬資料的 csv,在這個基本示例中,藍色突出顯示重疊點。那是因為許多公司具有相同的城市 gps 坐標。
![帶有傳單和 D3.js [問題] 的氣泡圖:氣泡重疊](https://img.uj5u.com/2022/05/19/e4b12c47789249c48c7d118b809081c6.png)
![帶有傳單和 D3.js [問題] 的氣泡圖:氣泡重疊](https://img.uj5u.com/2022/05/19/09f7655428e64f4696d2d5aae3eb156d.png)
這是我正在處理的代碼:
https
://jsfiddle.net/MathiasLauber/bckg8es4/45/ 后來的許多研究,我發現 d3.js 添加了這種力模擬功能,可以避免點碰撞。
// Avoiding bubbles overlapping
var simulationforce = d3.forceSimulation(data)
.force('x', d3.forceX().x(d => xScale(d.longitude)))
.force('y', d3.forceY().y(d => yScale(d.latitude)))
.force('collide', d3.forceCollide().radius(function(d) {
return d.radius 10
}))
simulationforce
.nodes(cities)
.on("tick", function(d){
node
.attr("cx", function(d) { return projection.latLngToLayerPoint([d.latitude, d.longitude]).x; })
.attr("cy", function(d) {return projection.latLngToLayerPoint([d.latitude, d.longitude]).y; })
});
問題是我無法進行強制布局,而且我的點仍然在彼此之上。(行:小提琴中的 188-200 行)。
如果您有任何提示、建議,或者您發現我的代碼中有基本錯誤,請告訴我 =D
一堆代碼接近我想要實作的目標
https://d3-graph-gallery.com/graph/circularpacking_group.html
https://jsbin.com/taqewaw/edit?html ,輸出
uj5u.com熱心網友回復:
有3個問題:
- 為了將圓定位在其原始位置附近,需要在傳遞給呼叫的資料中指定初始位置
x和初始位置。ysimulation.nodes() - 在進行力模擬時,您需要在 on tick 回呼中提供要模擬的選擇(參見
node回呼on('tick')函式)。 - 模擬需要使用模擬計算的先前
d.x和d.y值
下面的相關代碼片段
// 1. Add x and y (cx, cy) to each row (circle) in data
const citiesWithCenter = cities.map(c => ({
...c,
x: projection.latLngToLayerPoint([c.latitude, c.longitude]).x,
y: projection.latLngToLayerPoint([c.latitude, c.longitude]).y,
}))
// citiesWithCenter will be passed to selectAll('circle').data()
// 2. node selection you forgot
const node = selection
.selectAll('circle')
.data(citiesWithcenter)
.enter()
.append('circle')
...
// let used in simulation
simulationforce.nodes(citiesWithcenter).on('tick', function (d) {
node
.attr('cx', function (d) {
// 3. use previously computed x value
// on the first tick run, the values in citiesWithCenter is used
return d.x
})
.attr('cy', function (d) {
// 3. use previously computed y value
// on the first tick run, the values in citiesWithCenter is used
return d.y
})
})
完整的作業演示:https ://jsfiddle.net/b2Lhfuw5/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/477795.html
標籤:javascript d3.js 传单
