如何通过d3,提示显示所选的一级邻居(并且我的意思是在节点上盘旋)?
这是我的d3.tip部分
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(function(d) {return [name of neighbors];});
我如何更改关注以帮助我通过提示返回文字而不是更改不透明度?
var linkedByIndex = {};
var toggle = 0;
for (i = 0; i < nodes.length; i++) {
linkedByIndex[i + "," + i] = 1;
};
links.forEach(function (d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
//This function looks up whether a pair are neighbours
function neighboring(a, b) {
return linkedByIndex[a.index + "," + b.index];
}
function connectedNodes() {
if (toggle == 0) {
//Reduce the opacity of all but the neighbouring nodes
d = d3.select(this).node().__data__;
circle.style("opacity", function (o) {
return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
});
path.style("opacity", function (o) {
return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
});
//Reduce the op
toggle = 1;
} else {
//Put them back to opacity=1
circle.style("opacity", 1);
path.style("opacity", 1);
toggle = 0;
}}
答案 0 :(得分:1)
以下是我将如何使用不同的力导向图(应该很容易实现到你的)。
首次运行脚本时我会运行connectedNodes
函数,但是我不会更改不透明度,而是将邻居添加到数组中,然后将其附加到每个节点上的数据中。
这是一个工具提示(悬停时)的小提示,显示它连接到的所有节点(node.name):http://jsfiddle.net/reko91/jz2AU/125/
创建节点后运行该函数:
node.each(function(d) {
//console.log(d)
connectedNodes1(this)
})
这是改变的功能:
function connectedNodes1(thisNode) {
d = d3.select(thisNode).node().__data__;
var neighbours = [];
node.each(function(o) {
// console.log(o)
if (neighboring(d, o) | neighboring(o, d)) {
neighbours.push(o.name) //push into array
}
});
d3.select(thisNode).node().__data__.neighboursString =""; //set the attribute to nothing
for (i = 0; i < neighbours.length; i++) { //go through each element in the array to create one string
var thisString = neighbours[i] + ' | '; //add a split so it can be easily read
d3.select(thisNode).node().__data__.neighboursString += (thisString); //concat to attribute
}
d3.select(thisNode).node().__data__.neighbours = neighbours; //set neighbours to neighbours array above if you want to use any of the nodes later
}
注意我创建了两个属性:neighboursString
和neighbours
。
- neighboursString
:创建工具提示的所有邻居的连接
- neighbours
:所有邻居节点的数组(如果稍后需要)
现在创建工具提示(在第二个答案的帮助下:Show data on mouseover of circle)。显然,在你的情况下你不需要这个,所以只需将currentNode.neighboursString
传递给d3.tip,应该很简单:
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
现在在悬停时显示和编辑工具提示:
node.on("mouseover", function(d) {
tooltip.text(d.neighboursString); //set text to neighboursString attr
return tooltip.style("visibility", "visible");
})
.on("mousemove", function(d) {
tooltip.text(d.neighboursString);
return tooltip.style("top",
(d3.event.pageY - 10) + "px").style("left", (d3.event.pageX + 10) + "px");
})
.on("mouseout", function() {
return tooltip.style("visibility", "hidden");
});
希望能解决您的问题,您仍然可以在我显示的示例中双击邻居:)