How to hide labels with d3? - javascript

I am making a timeline sort of project. As of right now, my code looks like the following:
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-300)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("input.json", 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); })
.style("visibility", function(d) {
return d.value == 2 ? "hidden" : "visible";
});
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 20)
.style("fill", function(d) { return color(d.group); })
.call(force.drag)
.style("visibility", function(d) {
return d.group == 1 ? "hidden" : "visible";
})
.on("mouseover", function(d) {
if(d.group == 2) {
node.filter(function(d) { return d.group == 1; }).style("visibility", "visible");
link.filter(function(d) { return d.value == 2; }).style("visibility", "visible");
texts.filter(function(d) { return d.value == 2; }).style("visibility", "visible");
}
}).on("mouseout", function(d) {
if(d.group == 2) {
node.filter(function(d) { return d.group == 1; }).style("visibility", "hidden");
link.filter(function(d) { return d.value == 2; }).style("visibility", "hidden");
}
});
var texts = svg.selectAll("text.label")
.data(graph.nodes)
.enter().append("text")
.attr("class", "label")
.attr("fill", "black")
.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; });
texts.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
});
As of right now, the text, or labelsconstantly show, even when the nodes and links don't. I'm wondering what I need to do? I don't know if I can assign a value or group to the labels

Related

How to wrap text in force layout d3 with long labels?

I am trying to wrap text which is parsed from a json response into my application.
I have two svg elements : rect and text. I want to find a way where I can wrap my svg text such that it fits in the rectangle.
( Picture Force layout with text labels and rectangles )
This is the link to the original project in which I have made modifications
Visualizing Reddit Discussions
setupGraph();
function setupGraph() {
$(".network").empty();
names = {};
nodecolor = {};
force = d3.layout.force()
.charge(-500)
.linkDistance(20)
.size([width, height]);
nodes = force.nodes(),
links = force.links();
force.on("tick", function() {
svg.selectAll("line.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;
});
svg.selectAll("rect.node")
.attr("x", function(d) {
return d.x - d.curWidth / 2;
})
.attr("y", function(d) {
return d.y - d.curHeight / 2;
});
svg.selectAll("text.node")
.attr("x", function(d) {
return d.x - d.curWidth / 2 + 8;
})
.attr("y", function(d) {
return d.y - d.curHeight / 2 + 20;
});
});
d3.select("svg").remove();
svg = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.attr("class", "network");
}
function updateNetwork() {
var link = svg.selectAll("line.link")
.data(links, function(d) {
return d.source.id + "-" + d.target.id;
});
link.enter().insert("svg:line", "text.node", "rect.node")
.attr("class", "link")
.style("stroke-width", function(d) {
return 2;
})
.style("stroke", "gray")
.style("opacity", 0.1);
var node = svg.selectAll("rect.node")
.data(nodes, function(d) {
return d.id;
});
var node = svg.selectAll("text.node")
.data(nodes, function(d) {
return d.id;
});
var nodeEnter = node.enter().append("svg:rect")
.attr("class", "node")
.call(force.drag)
.attr("width", function(d) {
return d.curWidth;
})
.attr("height", function(d) {
return d.curHeight;
})
.style("opacity", 1.0)
.on("mouseover", displayTooltip)
.on("mousemove", moveTooltip)
.on("mouseout", removeTooltip)
.on("mouseover", function(d) {
d3.select(this).transition().attr("height", 100).attr("width", 100); //.style("fill", "red");
})
.call(force.drag)
var nodeEnterr = node.enter().append("svg:text")
.attr("class", "node")
.text(function(d) {
return d.name + ": " + d.body
})
.call(force.drag)
.style("opacity", 1.0)
.on("mouseover", displayTooltip)
.on("mousemove", moveTooltip)
.on("mouseout", removeTooltip)
.call(force.drag)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

d3 Node Labels and collapsing

I currently have a D3 that displays a force directed network and will collapse its children on click. I would like to to also display the names of the nodes on hover. Something like this: https://bl.ocks.org/mbostock/1212215
Below is my code so far.
.node {
cursor: pointer;
stroke: #3182bd;
stroke-width: 1.5px;
}
.link {
fill: none;
stroke: #9ecae1;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
root;
var force = d3.layout.force()
.size([width, height])
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
//Added markers to indicate that this is a directed graph
svg.append("defs").selectAll("marker")
.data(["arrow"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 4)
.attr("markerHeight", 4)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
d3.json("test.json", function(json) {
root = json;
//Give nodes ids and initialize variables
for(var i=0; i<root.nodes.length; i++) {
var node = root.nodes[i];
node.id = i;
node.collapsing = 0;
node.collapsed = false;
}
//Give links ids and initialize variables
for(var i=0; i<root.links.length; i++) {
var link = root.links[i];
link.source = root.nodes[link.source];
link.target = root.nodes[link.target];
link.id = i;
}
// for (var i=0; i<root.nodes.length; i++){
// var node = root.nodes[i];
// }
update();
});
function update() {
//Keep only the visible nodes
var nodes = root.nodes.filter(function(d) {
return d.collapsing == 0;
});
var links = root.links;
//Keep only the visible links
links = root.links.filter(function(d) {
return d.source.collapsing == 0 && d.target.collapsing == 0;
});
force
.nodes(nodes)
.links(links)
.start();
// Update the links…
link = link.data(links, function(d) { return d.id; });
// Exit any old links.
link.exit().remove();
// Enter any new links.
link.enter().insert("line", ".node")
.attr("class", "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; })
// Update the nodes…
node = node.data(nodes, function(d){ return d.id; }).style("fill", color);
// Exit any old nodes.
node.exit().remove();
// Enter any new nodes.
node.enter().append("circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; })
.style("fill", color)
.on("click", click)
.call(force.drag);
}
function tick() {
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; });
}
// Color leaf nodes orange, and packages white or blue.
function color(d) {
return d.collapsed ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}
// Toggle children on click.
function click(d) {
if (!d3.event.defaultPrevented) {
//check if link is from this node, and if so, collapse
root.links.forEach(function(l) {
if(l.source.id == d.id) {
if(d.collapsed){
l.target.collapsing--;
} else {
l.target.collapsing++;
}
}
});
d.collapsed = !d.collapsed;
}
update();
}
</script>
My issue is with the update function. I was able to get it to display, but when I clicked to collapse, it wouldn't show the labels after. Im not sure if I should be tweeting the tick or what.
thanks!
Group the circle and text labels using SVG group element as shown below.
var groupNodes = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; });
.on("click", click)
.on("mouseover", function(){
d3.select(this).select("text").style("display","block");
})
.on("mouseout", function(){
d3.select(this).select("text").style("display","none");
})
.call(force.drag);
groupNodes.append("circle")
.attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; })
.style("fill", color);
var label = groupNodes.append("text")
.attr("dy", ".35em")
.style("display", "none)
.text(function(d) { return d.name; //Use the key which holds the name value });
The above code replaces following part of the code in the update function.
node.enter().append("circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; })
.style("fill", color)
.on("click", click)
.call(force.drag);
and now change the tick function as follows
function tick() {
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("transform", function(d) {
return "translate("+d.x+","+d.y+")";
});
}
Now all other functionalities should work as expected.

3d.js - Updating nodes on a force directed graph

I am currently developing a program to create a graph(vertexes + edges) and apply an algorithm. I chose 3d.js to make this program.
I am confronted a problem about the repaintfunction when I add a vertex.
When I add the first vertex, it's work but for the following, my vertexes multiply rapidly(vertex&label)...
Screenshots:
Source code:
var graph = (function() {
return {
modules: {},
nodes: [],
links: []
}
})();
graph.modules.engin = (function() {
var w, h, circleWidth, svgApp, force, link, node, nodes;
var palette = {
"white": "#FFFFFF",
"gray": "#708284",
"orange": "#BD3613",
"red": "#D11C24",
"blue": "#2176C7"
};
return {
init: function() {
var w = 960,
h = 450;
circleWidth = 7;
svgApp = d3.select("body")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("id", "svg")
.attr("pointer-events", "all")
.attr("viewBox", "0 0 " + w + " " + h)
.attr("perserveAspectRatio", "xMinYMid")
.append('svg:g');
force = d3.layout.force()
.nodes(graph.nodes)
.links([])
.gravity(0.1)
.charge(-1000)
.size([w, h]);
//console.log(nodes);
//nodes.push({})
graph.modules.engin.repaint();
graph.modules.engin.insertNode('V1');
graph.modules.engin.insertNode('V2');
graph.modules.engin.insertNode('V3');
},
repaint: function() {
console.log('update');
nodes = force.nodes();
var links = force.links();
link = svgApp.selectAll(".link")
.data(links);
link.enter().append("line")
.attr("class", "link")
.attr("stroke", palette.gray)
.attr("fill", "none");
link.exit().remove();
node = svgApp.selectAll("circle.node")
.data(nodes);
node.enter().append("g")
.attr("class", "node")
.on("mouseover", function(d, i) { //MOUSEOVER
if (!d.root) {
d3.select(this).selectAll("circle")
.transition()
.duration(250)
.style("cursor", "none")
.attr("r", circleWidth + 3)
.attr("fill", palette.orange);
d3.select(this).select("text")
.transition()
.style("cursor", "none")
.duration(250)
.style("cursor", "none")
.attr("font-size", "1.5em")
.attr("x", 15)
.attr("y", 5)
} else {
d3.select(this).selectAll("circle")
.style("cursor", "none");
d3.select(this).select("text")
.style("cursor", "none");
}
})
.on("mouseout", function(d, i) { //MOUSEOUT
if (!d.root) {
//CIRCLE
d3.select(this).selectAll("circle")
.transition()
.duration(250)
.attr("r", circleWidth)
.attr("fill", palette.blue);
//TEXT
d3.select(this).select("text")
.transition()
.duration(250)
.attr("font-size", "1em")
.attr("x", 8)
.attr("y", 4)
}
})
.call(force.drag);
node.append("svg:circle")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("r", circleWidth)
.attr("fill", function(d, i) {
if (!d.root) {
return palette.blue;
} else {
return palette.red
}
});
node.append("text")
.text(function(d, i) {
return d.name;
})
.attr("x", function(d, i) {
return circleWidth + 5;
})
.attr("y", function(d, i) {
if (!d.root) {
return circleWidth
} else {
return circleWidth + 5
}
})
.attr("font-family", "Bree Serif")
.attr("fill", function(d, i) {
return palette.white;
})
.attr("font-size", function(d, i) {
return "1em";
})
.attr("text-anchor", function(d, i) {
if (!d.root) {
return "beginning";
} else {
return "end"
}
});
node.exit().remove();
force.on("tick", function(e) {
node.attr("transform", function(d, i) {
return "translate(" + d.x + "," + 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;
})
});
force.start();
},
insertNode: function(name) {
nodes.push({
name: name
})
graph.modules.engin.repaint();
}
}
})();
$(document).ready(function() {
graph.modules.engin.init();
});
html {
background-color: #042029;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button onclick="addNodes()">Restart Animation</button>
Thank you,
YM
I solved my problem: variable ref mistake and selector elements:
Source code:
var graph = (function() {
return {
modules: {},
nodes: [],
links: []
}
})();
graph.modules.engin = (function() {
var w, h, circleWidth, svgApp, force;
var palette = {
"white": "#FFFFFF",
"gray": "#708284",
"orange": "#BD3613",
"red": "#D11C24",
"blue": "#2176C7"
};
return {
init: function() {
h = $('body').height();
w = $('body').width();
circleWidth = 7;
svgApp = d3.select("body")
.append("svg:svg")
.attr("pointer-events", "all")
.attr("width", w)
.attr("height", h)
.attr("viewBox", "0 0 " + w + " " + h)
.attr("perserveAspectRatio", "xMinYMid");
force = d3.layout.force();
graph.nodes = force.nodes();
graph.links = force.links();
graph.modules.engin.repaint();
graph.modules.engin.insertNode('V1');
graph.modules.engin.insertNode('V2');
graph.modules.engin.insertNode('V3');
},
repaint: function() {
console.log('update');
var nodes = force.nodes();
var links = force.links();
console.log('BEFORE REPAINT');
console.log(nodes);
console.log(links);
console.log(graph.nodes);
console.log(graph.links);
var link = svgApp.selectAll("line.link")
.data(links);
var linkEnter = link.enter().append("line")
.attr("class", "link")
.attr("stroke", palette.gray)
.attr("fill", "none");
link.exit().remove();
var node = svgApp.selectAll("g.node")
.data(nodes, function(d) {
return d.name;
});
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.on("mouseover", function(d, i) {
if (!d.root) {
d3.select(this).select("circle")
.transition()
.duration(250)
.style("cursor", "none")
.attr("r", circleWidth + 3)
.attr("fill", palette.yellow);
d3.select(this) //.select("text")
.transition()
.style("cursor", "none")
.duration(250)
.style("cursor", "none")
.attr("font-size", "1.5em")
.attr("x", 15)
.attr("y", 5)
} else {
d3.select(this).select("circle")
.style("cursor", "none");
d3.select(this).select("text")
.style("cursor", "none");
}
})
.on("mouseout", function(d, i) {
if (!d.root) {
d3.select(this).select("circle")
.transition()
.duration(250)
.attr("r", circleWidth)
.attr("fill", palette.blue);
d3.select(this) //.select("text")
.transition()
.duration(250)
.attr("font-size", "1em")
.attr("x", 8)
.attr("y", 4)
}
})
.call(force.drag);
nodeEnter.append("svg:circle")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("r", circleWidth)
.attr("fill", function(d, i) {
if (!d.root) {
return palette.blue;
} else {
return palette.red
}
}).attr("id", function(d) {
return "Node-" + d.name;
});
nodeEnter.append("svg:text")
.text(function(d, i) {
return d.name;
})
.attr("x", function(d, i) {
return circleWidth + 5;
})
.attr("y", function(d, i) {
if (!d.root) {
return circleWidth - 2
} else {
return circleWidth + 5
}
})
.attr("font-family", "Bree Serif")
.attr("fill", function(d, i) {
return palette.white;
})
.attr("font-size", function(d, i) {
return "1em";
})
.attr("text-anchor", function(d, i) {
if (!d.root) {
return "beginning";
} else {
return "end"
}
});
node.exit().remove();
force.on("tick", function(e) {
node.attr("transform", function(d, i) {
return "translate(" + d.x + "," + 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;
})
});
force.gravity(0.1)
.charge(-1000)
.size([w, h])
.start();
},
insertNode: function(name) {
graph.nodes.push({
name: name
})
graph.modules.engin.repaint();
}
}
})();
$(document).ready(function() {
graph.modules.engin.init();
});
html {
background-color: #042029;
}
body {
height: 600px;
width: 100%;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button onclick="addNodes()">Restart Animation</button>

Labels and images for D3 nodes incorrectly show at top left of screen

I'm able to get images and labels to show for the nodes, but they show at the top left of the screen.
Nodes show up in the correct position when I use this
.enter().append("circle")
Labels and node images show at the top left (incorrect) when I use this:
.enter().append("g")
This works with append "circle" (commented out in the code below):
When I comment out append circle and use append "g" (in order to use node images and labels) the images and labels all show up near (0,0) instead of near the node:
Also, what exactly is append "g"? Where is the documentation to find out what's possible with append "g"?
Here is all the code:
<script>
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size(\[width, height\]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var graph = getData();
var nodeMap = {};
graph.nodes.forEach(function(d) { nodeMap\[d.name\] = d; });
graph.links.forEach(function(l) {
l.source = nodeMap\[l.source\];
l.target = nodeMap\[l.target\];
})
force.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke", function(d) {
return d.line_color;
})
.style("stroke-width", function(d) {
return Math.sqrt(d.value)+1;
});
var node = svg.selectAll(".node")
.data(graph.nodes)
// .enter().append("circle")
// .attr("class", "node")
// .attr("r", 10)
// .style("fill", function(d) { return d.fill_color; })
// .call(force.drag);
.enter().append("g")
.attr("class", "node")
.attr("r", 15)
.style("fill", function(d) { return d.fill_color; })
.on("click", function(d){
alert("You clicked on node " + d.name);
})
.call(force.drag);
node.append("title")
.text(function(d) { return d.label; });
node.append("image")
.attr("xlink:href", function(d) { return d.image_url })
.attr("x", -8)
.attr("y", -8)
.attr("width", 26)
.attr("height", 26);
node.append("text")
.attr("dx", function(d) {
if (d.image_url == "/profile.png"){
return 100;
}
else{
return 16;
}
})
.attr("dy", function(d) {
if (d.image_url == "/profile.png"){
return 100;
}
else{
return ".35em";
}
})
// .attr("dy", ".35em")
.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; });
});
function getData() {
return {
"nodes":\[
{"name":"user1","image_url":"http://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/103px-Wikipedia-logo-v2.svg.png","fill_color":"blue","text_color":"black"},
{"name":"user2","image_url":"http://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/103px-Wikipedia-logo-v2.svg.png","fill_color":"blue","text_color":"black"},
{"name":"user3","image_url":"http://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/103px-Wikipedia-logo-v2.svg.png","fill_color":"blue","text_color":"black"},
{"name":"tag1","image_url":"","fill_color":"blue","text_color":"black"},
{"name":"tag2","image_url":"","fill_color":"blue","text_color":"black"},
{"name":"tag3","image_url":"","fill_color":"blue","text_color":"black"}
\],
"links":\[
{"source":"tag1","target":"user1","value":1,"line_color":"green"},
{"source":"tag2","target":"user1","value":1,"line_color":"green"},
{"source":"tag3","target":"user1","value":1,"line_color":"green"},
{"source":"tag1","target":"user2","value":1,"line_color":"green"},
{"source":"tag2","target":"user2","value":1,"line_color":"green"}
\]
};
}
</script>
With .append("g") you insert a SVG Group Element.
The problem is, that you try to apply attributes that are for circles, like the radius with .attr("r",15), to the group element.
You have to use circles if you want to draw a circle. Group elements do not have any shape. They are used to group elements like circles.
A solution would be to append the g element and transform it to the location of the node. I updated your code in the following snippet. I used the group elements and added the circle, image and text inside the group elements.
Moreover I removed the backslashes before each angular bracket and set the title to the field name instead of label.
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var graph = getData();
var nodeMap = {};
graph.nodes.forEach(function(d) { nodeMap[d.name] = d; });
graph.links.forEach(function(l) {
l.source = nodeMap[l.source];
l.target = nodeMap[l.target];
})
force.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter()
.append("line")
.attr("class", "link")
.style("stroke", function(d) {
return d.line_color;
})
.style("stroke-width", function(d) {
return Math.sqrt(d.value)+1;
});
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter()
.append("g")
.attr("transform", function(d){return "translate("+d.x+","+d.y+")"})
.call(force.drag);
node.append("circle")
.attr("class", "node")
.attr("r", 15)
.style("fill", function(d) { return d.fill_color; })
.on("click", function(d){
alert("You clicked on node " + d.name);
});
node.append("title")
.text(function(d) { return d.name; });
node.append("image")
.attr("xlink:href", function(d) { return d.image_url })
.attr("x", -8)
.attr("y", -8)
.attr("width", 26)
.attr("height", 26);
node.append("text")
.attr("dx", function(d) {
if (d.image_url == "/profile.png"){
return 100;
}
else{
return 16;
}
})
.attr("dy", function(d) {
if (d.image_url == "/profile.png"){
return 100;
}
else{
return ".35em";
}
})
// .attr("dy", ".35em")
.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("transform", function(d){return "translate("+d.x+","+d.y+")"});
});
function getData() {
return {
"nodes":[
{"name":"user1","image_url":"http://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/103px-Wikipedia-logo-v2.svg.png","fill_color":"blue","text_color":"black"},
{"name":"user2","image_url":"http://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/103px-Wikipedia-logo-v2.svg.png","fill_color":"blue","text_color":"black"},
{"name":"user3","image_url":"http://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/103px-Wikipedia-logo-v2.svg.png","fill_color":"blue","text_color":"black"},
{"name":"tag1","image_url":"","fill_color":"blue","text_color":"black"},
{"name":"tag2","image_url":"","fill_color":"blue","text_color":"black"},
{"name":"tag3","image_url":"","fill_color":"blue","text_color":"black"}
],
"links":[
{"source":"tag1","target":"user1","value":1,"line_color":"green"},
{"source":"tag2","target":"user1","value":1,"line_color":"green"},
{"source":"tag3","target":"user1","value":1,"line_color":"green"},
{"source":"tag1","target":"user2","value":1,"line_color":"green"},
{"source":"tag2","target":"user2","value":1,"line_color":"green"}
]
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Static Force Directed Graph links not correct length [duplicate]

This question already has answers here:
d3.js linkStrength influence on linkDistance in a force graph
(2 answers)
Closed 2 years ago.
I am trying to create a static force directed graph. One that loads without any animation in. Here's what I'm trying to emulate: http://bl.ocks.org/mbostock/1667139
I have the following D3 graph:
var width = $("#theVizness").width(),
height = $("#theVizness").height();
var color = d3.scale.ordinal().range(["#ff0000", "#fff000", "#ff4900"]);
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("#theVizness").append("svg")
.attr("width", width)
.attr("height", height);
var loading = svg.append("text")
.attr("class", "loading")
.attr("x", width / 2)
.attr("y", height / 2)
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text("Loading...");
d3.json("https://dl.dropboxusercontent.com/u/5772230/ForceDirectData.json", function (error, json) {
var nodes = json.nodes;
force.nodes(nodes)
.links(json.links)
.linkDistance(function (d) {
return d.value * 1.5;
})
.friction(0.4);
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
var files = svg.selectAll(".file")
.data(json.nodes)
.enter().append("circle")
.attr("class", "file")
.attr("r", 10)
.attr("fill", function (d) {
return color(d.colorGroup);
});
var totalNodes = files[0].length;
files.append("title")
.text(function (d) { return d.name; });
force.start();
for (var i = totalNodes * totalNodes; i > 0; --i) force.tick();
force.stop();
nodes[0].x = width / 2;
nodes[0].y = height / 2;
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; });
files.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("class", function(d){
var classString = "file"
if (d.index === 0) classString += " rootFile";
return classString;
})
.attr("r", function(d){
var radius = 10;
if (d.index === 0) radius = radius * 2;
return radius;
});
loading.remove();
});
Here's my data: https://dl.dropboxusercontent.com/u/5772230/ForceDirectData.json
{
"nodes":[
{"name":"File1.exe","colorGroup":0},
{"name":"File2.exe","colorGroup":0},
{"name":"File3.exe","colorGroup":0},
{"name":"File4.exe","colorGroup":0},
{"name":"File5.exe","colorGroup":0},
{"name":"File6.exe","colorGroup":0},
{"name":"File7.exe","colorGroup":0},
{"name":"File8.exe","colorGroup":0},
{"name":"File8.exe","colorGroup":0},
{"name":"File9.exe","colorGroup":0}
],
"links":[
{"source":1,"target":0,"value":10},
{"source":2,"target":0,"value":35},
{"source":3,"target":0,"value":50},
{"source":4,"target":0,"value":50},
{"source":5,"target":0,"value":65},
{"source":6,"target":0,"value":65},
{"source":7,"target":0,"value":81},
{"source":8,"target":0,"value":98},
{"source":9,"target":0,"value":100}
]
}
Fiddle
From my understanding of the bl.ocks page, this graph is running the tick method a certain amount of times. But my issue is the lengths of my links between the nodes are not proportionate to what I have in my JSON file.
I've opted for the static graph because I did not want to have the graph animate in, like in the standard graph.
Why are my links to the nodes nor correctly proportioned to match my JSON file?
I do not understand your question.
Is this what you mean?
var width = $("#theVizness").width(),
height = $("#theVizness").height();
var color = d3.scale.ordinal().range(["#ff0000", "#fff000", "#ff4900"]);
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("#theVizness").append("svg")
.attr("width", width)
.attr("height", height);
var loading = svg.append("text")
.attr("class", "loading")
.attr("x", width / 2)
.attr("y", height / 2)
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text("Loading...");
d3.json("https://dl.dropboxusercontent.com/u/5772230/ForceDirectData.json", function (error, json) {
var nodes = json.nodes;
force.nodes(nodes)
.links(json.links)
.linkDistance(function (d) {
return d.value * 1.5;
})
.friction(0.4);
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
var files = svg.selectAll(".file")
.data(json.nodes)
.enter().append("circle")
.attr("class", "file")
.attr("r", 10)
.attr("fill", function (d) {
return color(d.colorGroup);
});
var totalNodes = files[0].length;
files.append("title")
.text(function (d) { return d.name; });
force.start();
for (var i = totalNodes * totalNodes; i > 0; --i) force.tick();
nodes[0].x = width / 2;
nodes[0].y = height / 2;
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; });
files.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("class", function(d){
var classString = "file"
if (d.index === 0) classString += " rootFile";
return classString;
})
.attr("r", function(d){
var radius = 10;
if (d.index === 0) radius = radius * 2;
return radius;
});
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; });
files.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
loading.remove();
});
JSFiddle

Categories