Is it possible to use names other than source and target for a D3 Force Directed Map? I am connecting to an API that provides me with the needed information but they are supplying it as 'src-port' and 'dst-port'. If I change the names in a static JSON file to 'source' and 'target' the links on my map appear. If I leave it as is, I get the following error message:
e.source is undefined
Is there a way I can specify what property names to look for instead of using the defaults, 'source' and 'target'?
Here is the complete code to work with:
function buildMap(node, ids, mode) {
d3.select("svg").remove();
width = 960,
height = 500;
svg = d3.select(node).append("svg")
.attr("width", width)
.attr("height", height)
.attr("id","chart")
.attr("preserveAspectRatio","xMidYMid")
.attr("viewBox","0 0 960 500");
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-220)
.linkDistance(40)
.size([width, height]);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d) {
return "<strong>DPID:</strong> <span style='color:red'>" + d.dpid + "</span><br />" + "<strong>Type:</strong> <span style='color:red'>" + d.type + "</span>";
})
svg.call(tip);
//d3.json("http://192.168.1.82:9000/wm/onos/topology", function(error, graph) {
d3.json("http://localhost:9001/data/nodes.json", function(error, graph) {
force
.nodes(graph.switches)
.links(graph.links.forEach(function(l) {
l.source = l["src-port"];
l.target = l["dst-port"];
})
)
.on("tick", tick)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll(".node")
.data(graph.switches)
.enter().append("circle")
.attr("class", function(d) {
//if(d.type == undefined) {
return "node";
//} else {
// return d.type;
//}
})
.attr("r", function(d) {
//if(d.type == undefined) {
return 5;
//} else {
// switch(d.type) {
// case "core":
// return 10;
// break;
// case "agg":
// return 8;
// break;
// default:
// return 5;
// }
//}
})
.style("fill", function(d) {
//var count = ids.length;
//if(count <= 0)
// return d.color;
var color = "#15a9ff";
//if(d3.select(this).style("fill") == color){
// for (i = 0; i <= count; i++) {
// if(ids[i] != undefined) {
// if(ids[i].attributes.id == d.instance_id) {
// color = d.color;
// }
// }
// }
return color;
// }
}
)
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.call(force.drag)
.on("click", function (d) {
enyo.Signals.send("onNodeSelected", d);
});
//node.append("title")
// .text(function(d) { return d.name; });
function tick(e) {
//if(mode == "tree") {
// var k = 6 * e.alpha;
// graph.links.forEach(function(d, i) {
// d.source.y -= k;
// d.target.y += k;
// });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
//} else {
// link.attr("x1", function(d) { return d.source.x; })
// .attr("y1", function(d) { return d.source.y; })
// .attr("x2", function(d) { return d.target.x; })
// .attr("y2", function(d) { return d.target.y; });
// node.attr("cx", function(d) { return d.x; })
// .attr("cy", function(d) { return d.y; });
}
//}
});
}
There is no way to do this through the API; you would have to modify the source. One easy way of dealing with this is to simply copy the values in src-port and dst-port into source and target:
links.forEach(function(l) {
l.source = l.src-port;
l.target = l.dst-port;
});
Related
I am using the below code for the iamges and mouseover text. And now i have added the code for double click on a node to fade out all but it is not working and also link color is not changing. Can anyone help on this
var width = 960,
height = 500
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.gravity(0.1)
.charge(-120)
.linkDistance(30)
.size([width, height]);
var voronoi = d3.geom.voronoi()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.clipExtent([[0, 0], [width, height]]);
d3.json("miserables1.json", function(error, json) {
if (error) throw error;
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link", "fill:red; stroke:red;");
var node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("svg:image")
.attr("xlink:href", function(d) { return d.imagen })
.on('dblclick', connectedNodes);
var circle = node.append("circle")
.attr("r", 4.5);
var label = node.append("text")
.attr("dy", ".35em")
.text(function(d) { return d.name; });
var cell = node.append("path")
.attr("class", "cell");
force.on("tick", function() {
cell
.data(voronoi(json.nodes))
.attr("d", function(d) { return d.length ? "M" + d.join("L") : null; });
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
circle
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
label
.attr("x", function(d) { return d.x + 8; })
.attr("y", function(d) { return d.y; });
});
});
var toggle = 0;
var linkedByIndex = {};
for (i = 0; i < graph.nodes.length; i++) {
linkedByIndex[i + "," + i] = 1;
};
graph.links.forEach(function (d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
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__;
node.style("opacity", function (o) {
return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
});
link.style("opacity", function (o) {
return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
});
toggle = 1;
} else {
node.style("opacity", 1);
link.style("opacity", 1);
toggle = 0;
}
}
I have created a d3 force layout, and it works very well. Now I will add a group of data to my graph. I hope I could control the center of my new nodes. For example, supposed the center is (100,100), I hope the new nodes lay out into rectangle area like [(50,50) to (150,150)] as a whole.
var width = 500,
height = 500;
var nodes = [{id:0, n:'Tom'}, {id:1, n:'Join'}, {id:2, n:'John'}, {id:3, n:'Bob'}, {id:4, n:'4'}, {id:5, n:'5'}, {id:6, n:'6'}];
var links = [{source:0,target:1},{source:0,target:2},{source:0,target:3},{source:0,target:4},{source:0,target:5},{source:1,target:5},{source:1,target:6}];
// init force
var force = d3.layout.force()
.charge(-120)
.linkDistance(120)
.size([width, height]);
// init svg
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// set tick function
force.on("tick", function () {
d3.selectAll(".link").attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
// controll the coordinates here
d3.selectAll(".node").attr("transform", function(d){
if(d.flag == 1){
d.x = Math.max(50, Math.min(150, d.x));
d.y = Math.max(50, Math.min(150, d.y));
}
return "translate("+d.x+","+d.y+")";
});
}).on('end', function(){
svg.selectAll(".node").each(function(d){d.fixed=true;});
});
function setData(ns, ls){
var update = svg.selectAll(".link").data(ls);
update.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
update.exit().remove();
update = svg.selectAll(".node").data(ns);
update.enter().append("g")
.attr("class", "node")
.attr("id", function(d){return d.id})
.call(force.drag)
.call(function(p){
p.append("image")
.attr("class", "nodeimage")
.attr("width", "30px")
.attr("height", "30px")
.attr("x", "-15px")
.attr("y", "-15px");
p.append("text")
.attr("class", "nodetext")
.attr("dx", "-10px")
.attr("dy", "20px")
.style("font-size", "15px")
.text(function(d){return d.n});
});
update.exit().remove();
update.selectAll(".nodeimage")
.each(function() {
d3.select(this).datum(d3.select(this.parentNode).datum());
})
.attr("xlink:href", function(d){
var img;
if(d.flag == 1){
img = "http://www.gravatar.com/avatar/1eccef322f0beef11e0e47ed7963189b/?default=&s=80"
}else{
img = "http://www.gravatar.com/avatar/a1338368fe0b4f3d301398a79c171987/?default=&s=80";
}
return img;
});
force.nodes(ns)
.links(ls)
.start();
}
//init
setData(nodes, links);
setTimeout(function(){
//generate new data and merge to old data
nodes = nodes.concat(generateNewData());
setData(nodes, links);
//how do i control the coordinate of new nodes?
}, 3000);
function generateNewData(){
var ns = [];
for(var i = 0; i < 10; i++){
ns.push({id:i+100,n:'n'+i,flag:1});
}
return ns;
}
Here is my demo of jsfiddle:http://jsfiddle.net/cs4xhs7s/4/
The latest demo shows that the nodes can display in the rectangle, however, their coordinates are the same. I hope it is an available force layout.
https://jsfiddle.net/wpnq15mf/1/
var width = 500,
height = 500;
var nodes = [{id:0, n:'Tom'}, {id:1, n:'Join'}, {id:2, n:'John'}, {id:3, n:'Bob'}, {id:4, n:'4'}, {id:5, n:'5'}, {id:6, n:'6'}];
var links = [{source:0,target:1},{source:0,target:2},{source:0,target:3},{source:0,target:4},{source:0,target:5},{source:1,target:5},{source:1,target:6}];
// init force
var force = d3.layout.force()
.charge(-500)
.linkDistance(120)
.gravity(0.1)
.size([width, height]);
// init svg
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// set tick function
force.on("tick", function () {
d3.selectAll(".link").attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
// controll the coordinates here
d3.selectAll(".node").attr("transform", function(d){
if(d.flag == 1){
d.x = Math.max(50, Math.min(150, d.x));
d.y = Math.max(50, Math.min(150, d.y));
}
return "translate("+d.x+","+d.y+")";
});
}).on('end', function(){
svg.selectAll(".node").each(function(d){d.fixed=true;});
});
function setData(ns, ls){
var update = svg.selectAll(".link").data(ls);
update.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
update.exit().remove();
update = svg.selectAll(".node").data(ns);
update.enter().append("g")
.attr("class", "node")
.attr("id", function(d){return d.id})
.call(force.drag)
.call(function(p){
p.append("image")
.attr("class", "nodeimage")
.attr("width", "30px")
.attr("height", "30px")
.attr("x", "-15px")
.attr("y", "-15px");
p.append("text")
.attr("class", "nodetext")
.attr("dx", "-10px")
.attr("dy", "20px")
.style("font-size", "15px")
.text(function(d){return d.n});
});
update.exit().remove();
update.selectAll(".nodeimage")
.each(function() {
d3.select(this).datum(d3.select(this.parentNode).datum());
})
.attr("xlink:href", function(d){
var img;
if(d.flagx == 1){
img = "http://www.gravatar.com/avatar/1eccef322f0beef11e0e47ed7963189b/?default=&s=80"
}else{
img = "http://www.gravatar.com/avatar/a1338368fe0b4f3d301398a79c171987/?default=&s=80";
}
return img;
});
force.nodes(ns)
.links(ls)
.start();
}
//init
setData(nodes, links);
setTimeout(function(){
//generate new data and merge to old data
nodes = nodes.concat(generateNewData());
links = links.concat(generateNewLinks());
setData(nodes, links);
//how do i control the coordinate of new nodes?
}, 3000);
function generateNewData(){
var ns = [];
ns.push({id:6,n:'n'+i,flag:1, flagx:1});
for(var i = 1; i < 10; i++){
ns.push({id:i+6,n:'n'+i, flagx:1});
}
return ns;
}
function generateNewLinks(){
var ns = [];
ns.push({source:7,target:8});
ns.push({source:7,target:9});
ns.push({source:7,target:10});
ns.push({source:7,target:11});
ns.push({source:7,target:12});
ns.push({source:7,target:13});
ns.push({source:7,target:14});
ns.push({source:7,target:15});
ns.push({source:7,target:16});
return ns;
}
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I am having an issue displaying a tooltip while changing the color of the element the tooltip is for. I can comment out the tooltip code and the stroke color will change for the element but I need both the tooltip and the class change to occur. Any help is greatly appreciated. Here is what I am talking about:
var svg = d3.select("#app_dataPlane")
.append("svg")
.attr("width", width)
.attr("height", height);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d) {
return "<strong>DPID:</strong> <span style='color:red'>" + d.name + "</span><br />" + "<strong>State:</strong> <span style='color:red'>" + d.state + "</span>";
})
svg.call(tip);
var link = svg.selectAll(".link")
.data(topoObj.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", 2)
.on("mouseover", function (d) {
d3.selectAll(".link").classed("selectedLink", false);
d3.select(this).classed("selectedLink", true);
d3.select("#app_srcSwitch").html(d.source.name);
d3.select("#app_destSwitch").html(d.target.name);
});
var node = svg.selectAll(".switch")
.data(topoObj.nodes)
.enter()
.append("circle")
.attr("r", 6)
.attr("stroke", "white")
.attr("class","switch")
.attr("fill", function (d) {
if (d.group == 1) {
return "#15a9ff";
} else if (d.group == 2) {
return "#f98802";
} else if (d.group == 3) {
return "#ca5eff";
} else if (d.group == 4) {
return "#37a302";
} else if (d.group == 5) {
return "#00a4b0";
} else if (d.group == 6) {
return "#ff6054";
} else if (d.group == 7) {
return "#7b75ff";
} else if (d.group == 8) {
return "#b77264";
} else {
return "#8c8c8c";
}
})
.on('mouseover', function (d) {
d3.selectAll(".switch").classed("selectedSwitch", false);
d3.select(this).classed("selectedSwitch", true);
d3.select("#app_stateInfo").html(d.state);
d3.select("#app_dpidInfo").html(d.name);
d3.select("#app_InstanceInfo").html(d.onosInstance);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.call(force.drag);
Subsequent calls to .on("mouseover", ...) overwrite what you've set there previously. To combine several things, execute them all in the handler function:
.on('mouseover', function (d) {
d3.selectAll(".switch").classed("selectedSwitch", false);
d3.select(this).classed("selectedSwitch", true);
d3.select("#app_stateInfo").html(d.state);
d3.select("#app_dpidInfo").html(d.name);
d3.select("#app_InstanceInfo").html(d.onosInstance);
tip.show();
});
I am attempting to send in a set of IDs to my method that builds my Force Directed map. I loop through the nodes and I want to set the fill color of the nodes that are selected from the parent id. I have a list on the page where when you select an item from it it will highlight the additional nodes by matching the color. I can't seem to get the fill color right. Any help is greatly appreciated.
<code>
function buildAllForceDirectedMultiMap(node, ids) {
d3.select("svg").remove();
var width = 960,
height = 500;
var svg = d3.select(node).append("svg")
.attr("width", width)
.attr("height", height);
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d) {
return "<strong>DPID:</strong> <span style='color:red'>" + d.dpid + "</span><br />" + "<strong>Type:</strong> <span style='color:red'>" + d.type + "</span>";
})
svg.call(tip);
d3.json("http://atxapps.com/apps/data/onos/dataGetFDAllInstances.php", function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", function(d) {
if(d.type == undefined) {
return "node";
} else {
return d.type;
}})
.attr("r", function(d) {
if(d.type == undefined) {
return 5;
} else {
switch(d.type) {
case "core":
return 10;
break;
case "agg":
return 8;
break;
default:
return 5;
}
}})
.style("fill", function(d) {
var count = ids.length;
for (i = 0; i <= count; i++) {
if(ids[i] != undefined) {
if(ids[i].attributes.id == d.instance_id) {
return d.color;
} else {
return "#2a2a2a";
}}
}
return d.color;
}
)
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.call(force.drag)
.on("click", function (d) {
//alert(d.dpid);
});
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
}
</code>
wound up having to select the instance of the d3 element I was working with. Code looks like this now
<pre>
.style("fill", function(d) {
var count = ids.length;
var color = "rgb(0, 0, 0)";
if(d3.select(this).style("fill") == color){
for (i = 0; i <= count; i++) {
if(ids[i] != undefined) {
if(ids[i].attributes.id == d.instance_id) {
color = d.color;
}
}
}
return color;
}
}
)
</pre>
I would like to highlight the edges of a graph when the connected nodes are hovered.
I took inspiration from the Bundle example:
However the on() function is not giving the d object to the onmouse function:
d3.json("graph_file.json", function(json) {
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll("line.link")
.data(json.links)
.enter().append("line")
.attr("class", function(d) { return "link source-" + d.source.key + " target-" + d.target.key; })
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", function(d) { return d.connec; })
.style("fill", function(d) { return color(d.group); })
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.call(force.drag);
...
function mouseover(d) {
svg.selectAll("line.link.target-" + d.key)
.classed("target", true);
svg.selectAll("line.link.source-" + d.key)
.classed("source", true);
}
any help appreciated.
Ultimately I was not able to reproduce your problem! The only thing that caught me at first was when I defined my mouseover and mouseout functions after setting them in .on(...) In that case they were undefined for the call and no mouse handlers were set - so the functions were simply never called.
Anyway, you can see what I tried here. The code:
var w = 400,
h = 400;
var vis = d3.select("svg").attr("width", 800).attr("height", 800);
var nodes = [];
var links = [];
for (var i = 0; i < 30; i++) {
var node = {
label: "node " + i,
value: Math.random(),
key: i
};
nodes.push(node);
};
for (var i = 0; i < nodes.length; i++) {
for (var j = 0; j < i; j++) {
if (Math.random() > .95) links.push({
source: nodes[i],
target: nodes[j],
weight: Math.random()
});
}
};
var force = d3.layout.force().size([w, h]).nodes(nodes).links(links);
force.start();
var link = vis.selectAll("line.link").data(links).enter().append("line").style("stroke", "#CCC").attr("class", function(d) {
return "link source-" + d.source.key + " target-" + d.target.key;
});
var mouseover = function(d) {
txt.text(JSON.stringify(d));
//txt.text("line.link.target-" + d.key);
vis.selectAll("line.link.target-" + d.key).classed("target", true).style("stroke", '#F00');
vis.selectAll("line.link.source-" + d.key).classed("source", true).style("stroke", '#F00');
}
var mouseout = function(d) {
vis.selectAll("line.link.target-" + d.key).classed("target", false).style("stroke", "#CCC");
vis.selectAll("line.link.source-" + d.key).classed("source", false).style("stroke", "#CCC");
}
var node = vis.selectAll("circle.node").data(force.nodes()).enter().append("circle").attr("class", "node").attr("r", 5).style("fill", function(d) {
return d3.rgb(55 * d.value, 255 * d.value, 155 * d.value)
}).style("stroke", "#FFF").style("stroke-width", 3).on("mouseover", mouseover).on("mouseout", mouseout).call(force.drag);
var txt = vis.append('text').attr({
transform: 'translate(5,400)'
}).text("Node Info");
var updateLink = function() {
this.attr("x1", function(d) {
return d.source.x;
}).attr("y1", function(d) {
return d.source.y;
}).attr("x2", function(d) {
return d.target.x;
}).attr("y2", function(d) {
return d.target.y;
});
}
var updateNode = function() {
this.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
force.on("tick", function() {
node.call(updateNode);
link.call(updateLink);
});