【发布时间】:2018-09-27 17:07:09
【问题描述】:
我有一个多焦点布局,但找不到动态设置焦点的方法。
在下面使用数据子集的代码中,我希望能够在 id-group 和熟悉度之间切换,这会将图表从 3 个气泡簇更改为 5 个气泡簇。当前焦点是硬编码的,这会阻止切换工作。
var data = [
{"id": 0, "name": "AngularJS", "familiarity":0,"r": 50 },
{"id": 0, "name": "HTML5", "familiarity":1,"r": 40 },
{"id": 0, "name": "Javascript", "familiarity":2,"r": 30 },
{"id": 1, "name": "Actionscript","familiarity":0, "r": 50 },
{"id": 1, "name": "Flash", "familiarity":4, "r": 32 },
{"id": 2, "name": "Node Webkit", "familiarity":3,"r": 40 },
{"id": 2, "name": "Chrome App", "familiarity":3,"r": 30 },
{"id": 2, "name": "Cordova", "familiarity":0,"r": 45 },
];
var width = window.innerWidth,
height = 450;
var fill = d3.scale.category10();
var nodes = [], labels = [],
foci = [{x: 0, y: 150}, {x: 400, y: 150}, {x: 200, y: 150}];
var svg = d3.select("body").append("svg")
.attr("width", "100%")
.attr("height", height)
//.attr("domflag", '');
var force = d3.layout.force()
.nodes(nodes)
.links([])
.charge(-200)
.gravity(0.1)
.friction(0.8)
.size([width, height])
.on("tick", tick);
var node = svg.selectAll("g");
var counter = 0;
function tick(e) {
var k = .3 * e.alpha;
// Push nodes toward their designated focus.
nodes.forEach(function(o, i) {
o.y += (foci[o.id].y - o.y) * k;
o.x += (foci[o.id].x - o.x) * k;
});
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
var timer = setInterval(function(){
if (nodes.length > data.length-1) { clearInterval(timer); return;}
var item = data[counter];
nodes.push({id: item.id, r: item.r, name: item.name});
force.start();
node = node.data(nodes);
var n = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.style('cursor', 'pointer')
.on('mousedown', function() {
var sel = d3.select(this);
sel.moveToFront();
})
.call(force.drag);
n.append("circle")
.attr("r", function(d) { return d.r/2; })
.style("fill", function(d) { return fill(d.id); })
n.append("text")
.text(function(d){
return d.name;
})
.style("font-size", function(d) {
return Math.min(2 * d.r, (2 * d.r - 8) / this.getComputedTextLength() * 16) + "px";
})
.attr("dy", ".35em")
counter++;
}, 100);
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
};
function resize() {
width = window.innerWidth;
force.size([width, height]);
force.start();
}
d3.select(window).on('resize', resize);
circle {
stroke: #fff;
}
<script src="//d3js.org/d3.v3.min.js"></script>
如何动态设置foci的坐标,如果是3-4簇,就对齐一行,如果是10簇,就做成3行小倍数?
谢谢。
【问题讨论】:
标签: javascript d3.js force-layout