I am not sure if this has been done (or can be done) since I have not seen any examples or questions regarding it but I will try to explain as best as I can.
I have a d3 force graph where I am trying to give it the functionality to "expand". Example: I have a JSON with
{
"nodes": [
{"name":"p1"},
{"name":"p2"},
{"name":"p3"},
{"name":"p4"}
],
"links": [
{"source":"p1","target":"p2"},
{"source":"p1","target":"p3"},
{"source":"p3","target":"p2"},
{"source":"p3","target":"p4"}
]}
So if a user selects node p3 and selects expand. It sends a request and we get a JSON back that can comes in with new nodes and links (but can also contain duplicates). ie,
{
"nodes": [
{"name":"p3"},
{"name":"p4"},
{"name":"p5"},
{"name":"p6"}
],
"links": [
{"source":"p3","target":"p4"},
{"source":"p4","target":"p5"},
{"source":"p4","target":"p6"}
]}
Since I wasn't sure if this could be done in d3 in the first place. I tested the functionality by just appending the new JSON data to the old JSON data (dupes and all). Now I assumed that d3 would check for duplicates already in the graph (like p3 to p4) but after appending, when I run the graph all p3 p4 p5 and p6 are just floating in space with no links even though I specified the links and it created p3 p4 node even though it already was there. (The initial graph with the 4 nodes still built and was linked properly).
So is the functionality possible to perform in d3? I have seen people who want to have multiple graphs on the screen but I am doing more of like an overlap/merge.
I have tried having my initial graph created then I use a test where I press a button and I read it in another JSON but it breaks or just doesn't create anything.
My code:
// Define the dimensions of the visualization.
var width = innerWidth,
height = innerHeight,
color = d3.scale.category20(),
root;
// Create an array logging what is connected to what
var linkedByIndex = { };
// Create the SVG container for the visualization and define its dimensions
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node"),
linkText;
// Mouse Event Variables
var selected_node = null,
selected_link = null,
mousedown_node = null,
mousedown_link = null,
mouseup_node = null;
// Create the force layout
var force = d3.layout.force()
.size([width, height])
.charge(-650)
.linkDistance(80);
var jsonStack = { };
var jsonCount = 0;
var jsonPath1 = "../../test/resources/cytoscape.json";
var jsonPath2 = "../../test/resources/cytoscapeexpand.json";
// Read in the JSON data.
d3.json(jsonPath1, function (error, json) {
// expands scope of json
jsonStack[jsonCount] = json;
root = jsonStack[jsonCount];
console.log("Successfully loaded" + json);
//console.log(JSON.stringify(root));
update();
jsonCount += 1;
});
d3.select('#expand').on("click", function() {
d3.json(jsonPath2, function(error, json) {
// expands scope of json
root = json
update();
});
});
function update() {
// sets the source and target to use id instead of index
root.edges.forEach(function(e) {
var sourceNode = root.nodes.filter(function(n) {
return n.data.id === e.data.source;
})[0],
targetNode = root.nodes.filter(function(n) {
return n.data.id === e.data.target;
})[0];
// push the EDGE attributes in the JSON to the edges array.
edges.push({
source: sourceNode,
target: targetNode,
label: e.data['label'],
color: e.data['color']
});
});
force
.nodes(root.nodes)
.links(edges)
.start();
link = link
.data(edges)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1.5);
node = node
.data(root.nodes)
.enter().append("g")
.attr("class", "node")
//.attr("fixed", function(d) { return d.fixed=true })
.call(force.drag)
.on('mouseover', connectedNodes)
.on('mouseleave', restore)
.on('dblclick', highlight);
node.append("circle").attr("r", 11);
node.style("fill", function(d) { return d.data['color'] }).select("circle").style("stroke", "black");
link.style("stroke", function(d) { return d.color });
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.style("fill", "black")
.text(function (d) { return d.data['label']; });
root.edges.forEach(function (d) {
linkedByIndex[d.data.source + "," + d.data.target] = 1;
});
resize();
window.addEventListener('resize', resize);
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 + ")"; });
});
}
// Highlighting of selected node.
function highlight(d) {
if (d.selected == false) {
d.selected = true;
return d3.select(this).style("fill", "yellow");
}
else {
d.selected = false;
return d3.select(this).style("fill", d.data['color']);
}
update();
}
Related
its my json
var data =
[{
name:"Words",
children:[{
name:"Nouns",
children:[
{
name:"Table",
size:1025
},
{
name:"Box",
size:2925
},
{
name:"Bat",
size:4025
},
],
size: 2000
},
{
name:"Adverbs",
children:[
{
name:"eagerly",
size:2520
},
{
name:"badly",
size:3259
},
{
name:"easily",
size:2512
},
],
size: 425
},
{
name:"Adjectives",
children:[
{
name:"Positive",
children:[
{
name:"Amazing",
size:1250
},
{
name:"Beautiful",
size:2529
}],
size:1000
},
{
name:"Negative",
children:[
{
name:"Destructive",
size:1250
},
{
name:"Hot",
size:2529
}],
size:1000
},
],
size: 343
},
{
name:"Verbs",
children:[
{
name:"Play",
size:4310
},
{
name:"Say",
size:2943
},
{
name:"Ride",
size:4430
},
],
size: 343
},
],
size: 2000
}];
initialized with null
var g = {
data: null,
force: null
};
created graph
$(function () {
//use a global var for the data:
g.data = data;
var width = 1300,
height = 630;
//Create a sized SVG surface within viz:
var svg = d3.select("#viz")
.append("svg")
.attr("width", width)
.attr("height", height);
g.link = svg.selectAll(".link"),
g.node = svg.selectAll(".node");
//Create a graph layout engine:
g.force = d3.layout.force()
.linkDistance(150)
.charge(-300)
.gravity(0.01)
.size([width, height])
//that invokes the tick method to draw the elements in their new location:
.on("tick", tick);
//Draw the graph:
//Note that this method is invoked again
//when clicking nodes:
update();
});
function update() {
//iterate through original nested data, and get one dimension array of nodes.
var nodes = flatten(g.data);
//Each node extracted above has a children attribute.
//from them, we can use a tree() layout function in order
//to build a links selection.
var links = d3.layout.tree().links(nodes);
// pass both of those sets to the graph layout engine, and restart it
Here is where error occur
g.force.nodes(nodes) //Here is where error occur
.links(links)
.start();
///////////////////////////////////////////////////////////////////
//-------------------
// create a subselection, wiring up data, using a function to define
//how it's suppossed to know what is appended/updated/exited
g.link = g.link.data(links, function (d) {return d.target.id;});
//Get rid of old links:
g.link.exit().remove();
//Build new links by adding new svg lines:
g.link
.enter()
.insert("line", ".node")
.attr("class", "link");
// create a subselection, wiring up data, using a function to define
//how it's suppossed to know what is appended/updated/exited
g.node = g.node.data(nodes, function (d) {return d.id;});
//Get rid of old nodes:
g.node.exit().remove();
//-------------------
//create new nodes by making groupd elements, that contain circls and text:
var nodeEnter = g.node.enter()
.append("g")
.attr("class", "node")
.on("click", click)
.call(g.force.drag);
//circle within the single node group:
nodeEnter.append("circle")
.attr("r", function (d) {return Math.sqrt(d.size) || 50;});
//text within the single node group:
nodeEnter.append("text")
.attr("dy", ".35em")
.text(function (d) {
return d.name;
});
//All nodes, do the following:
g.node.select("circle")
.style("fill", color); //calls delegate
//-------------------
}
// Invoked from 'update'.
// The original source data is not the usual nodes + edge list,
// but that's what's needed for the force layout engine.
// So returns a list of all nodes under the root.
function flatten(data) {
var nodes = [],
i = 0;
//count only children (not _children)
//note that it doesn't count any descendents of collapsed _children
//rather elegant?
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(data);
//Done:
return nodes;
}
update();
//Invoked from 'update'
//Return the color of the node
//based on the children value of the
//source data item: {name=..., children: {...}}
function color(d) {
return d._children ? "#3182bd" // collapsed package
:
d.children ? "#c6dbef" // expanded package
:
"#fd8d3c"; // leaf node
}
// Toggle children on click by switching around values on _children and children.
function click(d) {
if (d3.event.defaultPrevented) return; // ignore drag
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
//
update();
}
//event handler for every time the force layout engine
//says to redraw everthing:
function tick() {
width=1300;
height=630;
r=60;
g.node.attr("cx", function(d) { return d.x = Math.max(r, Math.min(width - r, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(r, Math.min(height - r, d.y)); });
//redraw position of every link within the link set:
g.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;
});
//same for the nodes, using a functor:
g.node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
**Whenever i add my new json with the same format it doesnt show anything. and the error tracebacks to the code the == update(); ==
jquery version: 2.1.3
d3 version : 3.4.13
dont know if it matters or not but i am intergrating this in http://metroui.org.ua/
Metro Ui tabs
Please help!**
I am trying to get values from the "links" instead of "nodes. I guess a more helpful way of asking this is how to specify where I am requesting getting the values from my JSON.
JSON for reference:
{
"nodes": [
{"fixed":true,"data": {"id": "foo","idType":"USERNAME","color":"red"},"selected":false},
{"fixed":true,"data": {"id": "bar","idType":"USERNAME","color":"yellow"},"selected": false}
],
"links": [
{"classes":null,"data":{"color":"blue","source":"foo","target":"bar","visible":true},"grabbable":false},
{"classes":null,"data":{"color":"green","source":"bar","target":"foo","visible":true},"grabbable":false}
]}
So an example is I can get this to work
node.style("fill", function(d) { return d.data['color'] });
but not
link.style("stroke", function(d) { return d.data['color'] });
However, this works...
link.style("stroke", "red"});
In the console it says d.data['color'] is undefined. I guess I do not understand how it is being called exactly. I have seen some examples of code that has
function(d, i) { return bla bla }
and I assumed that if d is always node, maybe i might be edges but adding that to my code didn't do much. If someone could explain what the i is touching that would be good also.
Code snippet of actual code below:
// Define the dimensions of the visualization.
var width = innerWidth,
height = innerHeight,
color = d3.scale.category20(),
root;
// Create an array logging what is connected to what
var linkedByIndex = { };
// Create the SVG container for the visualization and define its dimensions
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");
// Create the force layout
var force = d3.layout.force()
.size([width, height])
.charge(-400)
.linkDistance(50);
//Read in the JSON data.
d3.json("../test/resources/full.json", function(error, json) {
// expands scope of json
root = json
alert(root)
update();
});
function update() {
// sets the source and target to use id instead of index
var edges = [];
root.links.forEach(function(e) {
var sourceNode = root.nodes.filter(function(n) {
return n.data.id === e.data.source;
})[0],
targetNode = root.nodes.filter(function(n) {
return n.data.id === e.data.target;
})[0];
edges.push({
source: sourceNode,
target: targetNode
});
});
force
.nodes(root.nodes)
.links(edges)
.start();
link = link
.data(edges)
.enter().append("line")
.attr("class", "link");
node = node
.data(root.nodes)
.enter().append("g")
.attr("class", "node")
//.attr("fixed", function(d) { return d.fixed=true })
.call(force.drag)
.on('mouseover', connectedNodes)
.on('mouseleave', restore)
.on('click', highlight);
// Checks for the shape and color to be made for the node.
node.append("circle")
.attr("r", 10);
node.style("fill", function(d) { return d.data['color'] });
link.style("stroke", function(d) { return d.data['color'] });
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.style("fill", "black")
// Checks what to return as the node label based on idType.
.text(function (d) {
if (d.data['idType']==="Comment") {
return d.data.attrs[1].val;
}
else if(d.data['idType']==="MEDIA") {
return "MEDIA " + d.data['id'];
}
else
return d.data['id'];
});
root.links.forEach(function (d) {
linkedByIndex[d.data.source + "," + d.data.target] = 1;
});
resize();
window.addEventListener('resize', resize);
}
Per Lars' comment, edges does not contain the original link data. So it was currently pushing only
edges.push({
source: sourceNode,
target: targetNode
});
so to add any information that isn't in my edges I would have to add it. An example is if I were to push the color attribute from JSON my code would look like
edges.push({
source: sourceNode,
target: targetNode,
color: e.data['color']
});
So I have a d3.js force-directed graph that displays data from a JSON feed. When I click a node I requested an updated JSON feed based off the node that was clicked.
The JSON that is returned is correct. But what displays in the graph does not reflect what data is held in the JSON. I have a feeling the graph is holding onto previous graph data.
Heres a quick gif that should help visualise the issue.
Here is a JSFiddle to give you an idea of how to graph currently works.
And the Javascript on its own is at the bottom of this question.
In a bit more detail. When you click a node, it passes the word that node is associated with into a query string of a URL. I then run the d3.json using this new 'clicked' url and run an update function to recreate the graph.
So an example of how this is wrong. So if you go onto the JSFiddle and click on the node called 'piercingly' you will find that the next graph that is loaded doesn't even have the word 'piercingly' in it, and still has labels associated to bitter (the original search). Yet it if you change the variable at the top of the JS to 'piercingly' a different but correct graph is loaded.
The number of nodes is correct. But the label and other attributes in the full version (not the version on JSFiddle) are incorrect.
Any help would be much appreciated.
$wordToSearch = "bitter";
var w = 960,
h = 960,
node,
link,
root,
title;
var jsonURL = 'http://desolate-taiga-6759.herokuapp.com/word/basic/' + $wordToSearch;
d3.json(jsonURL, function(json) {
root = json.words[0]; //set root node
root.fixed = true;
root.x = w / 2;
root.y = h / 2 - 80;
update();
});
var force = d3.layout.force()
.on("tick", tick)
.charge(-700)
.gravity(0.1)
.friction(0.9)
.linkDistance(50)
.size([w, h]);
var svg = d3.select(".graph").append("svg")
.attr("width", w)
.attr("height", h);
//Update the graph
function update() {
var nodes = flatten(root),
links = d3.layout.tree().links(nodes);
// Restart the force layout.
force
.nodes(nodes)
.links(links)
.start();
// Update the links…
link = svg.selectAll("line.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links.
link.enter().insert("svg: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; });
// Exit any old links.
link.exit().remove();
// Update the nodes…
node = svg.selectAll(".node")
.data(nodes);
var nodeE = node
.enter();
var nodeG = nodeE.append("g")
.attr("class", "node")
.call(force.drag);
nodeG.append("circle")
.attr("r", 10)
.on("click", click)
.style("fill", "red");
nodeG.append("text")
.attr("dy", 10 + 15)
.attr("text-anchor", "middle")
.text(function(d) { return d.word });
node.exit().remove();
}
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 + ")"; });
}
/***********************
*** CUSTOM FUNCTIONS ***
***********************/
//Request extended JSON objects when clicking a clickable node
function click(d) {
$wordClicked = d.word;
var jsonURL = 'http://desolate-taiga-6759.herokuapp.com/word/basic/' + $wordClicked;
console.log(jsonURL);
updateGraph(jsonURL);
}
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) node.size = node.children.reduce(function(p, v) { return p + recurse(v); }, 0);
if (!node.id) node.id = ++i;
nodes.push(node);
return node.size;
}
root.size = recurse(root);
return nodes;
}
//Update graph with new extended JSON objects
function updateGraph(newURL) {
d3.json(newURL, function(json) {
root = json.words[0]; //set root node
root.fixed = true;
root.x = w / 2;
root.y = h / 2 - 80;
update();
});
}
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
EDIT: So I tried logging out the word when it is added to the text element. On first load all the words get logged as the get assigned to their respected text element. But when you click on the node, they don't. (Please see gif below). This is strange as I called the update function on click. So the word (in theory) should be fetched again for that node. But it doesnt.
It's quite hard to grasp on a phone but I think the reason is probably because it's getting confused about the new data. By default the data() function uses the index of the item to join to the DOM.
What you need to do instead is pass another function to your calls to data() which is described as a key function. Here you can probably just return the word.
.data(nodes, function(d) { return d.word; })
Take a look at the data function in the API docs https://github.com/mbostock/d3/wiki/Selections . I've had complex cases catch me out a couple of times where I missed a key function.
I'm attempting to put multiple D3 force layouts on a page at the same time. The number of force layouts is ideally variable, depending on the number of roots returned from a dynamic API. I have followed the answers on this question regarding multiple force layouts and have successfully put each layout in a separate div, in a separate svg.
However, the issue is twofold:
1) The svgs seem to be drawn at the same time, causing conflicts in the alpha cooling parameter (on "tick" of each graph). Thus, the only layout that is positioned the way it is intended is the last svg drawn on the page. The tick function contains code that shapes the force layout similar to a weeping willow tree, with the root node sitting on top and the children falling below it.
2) Setting a loop to iterate on the full results list from the API causes D3 to crash, and an error "Uncaught TypeError: Cannot read property 'textContent' of null."
I think the ideal solution would be to draw each force layout after the previous one has been successfully rendered, in a way that does not cause the alpha cooling parameters (on "tick") to conflict, or overloading the D3 library with too many instances of the force layout at once. Does someone have insight into this issue? Here is my code:
/* ... GET THE RESULTS FROM THE API ...*/
function handleRequest2(json) {
allroots = json[1]['data']['children'];
(function() {
var index = 0;
function LoopThrough() {
currentRoot = allroots[index];
if (index < allroots.length) {
/* DRAW THE GRAPH */
draw_graphs(currentRoot, index);
++index;
LoopThrough();
};
}
LoopThrough();
})();
}
//Force Layout Code
function draw_graphs(root, id) {
var root_id = "map-" + id.toString();
var force;
var vis;
var link;
var node;
var w = 980;
var h = 1000;
var k = 0;
// Create a separate div to house each SVG graph
div = document.createElement("div");
div.style.width = "980px";
div.style.height = "1000px";
div.style.cssFloat="left";
div.id = root_id;
$(div).addClass("chattermap-map");
// Append the div to the chart container
$('#chart').append(div);
force = d3.layout.force()
.size([w, h])
.charge(-250)
.gravity(0)
.on("tick", tick);
// Create the SVG and append it to the created div
vis = d3.select("#"+root_id)
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("id",root_id);
// Put the Reddit JSON in the correct format for the Force Layout
nodes = flatten(root),
links = optimize(d3.layout.tree().links(nodes));
// Calculations for the sizing of the nodes
avgNetPositive = getAvgNetPositive();
maxNetPositive = d3.max(netPositiveArray);
minNetPositive = d3.min(netPositiveArray);
// Create a logarithmic scale that sizes the nodes
radius = d3.scale.pow().exponent(.3).domain([minNetPositive,maxNetPositive]).range([5,30]);
// Fix the root node to the top of the svg
root.data.fixed = true;
root.data.x = w/2;
root.data.y = 50;
// Start the force layout.
force
.nodes(nodes)
.links(links)
.start();
// Update the links
link = vis.selectAll("line.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links.
link.enter().insert("svg: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; });
// Exit any old links.
link.exit().remove();
// Update the nodes
node = vis.selectAll("circle.node")
.data(nodes, function(d) {return d.id; })
.style("fill", function(d) {
return '#2960b5';
});
// Enter any new nodes.
node.enter().append("svg:circle")
.attr("class", "node")
.attr("cx", function(d) {return d.x; })
.attr("cy", function(d) {return d.y; })
.attr("r", function(d) {
//Get the net positive reaction
var netPositive = d.ups - d.downs;
var relativePositivity = netPositive/avgNetPositive;
//Scale the radii based on the logarithmic scale defined earlier
return radius(netPositive);
})
.style("fill", function(d) {
return '#2960b5';
})
// Allow dragging on click
.call(force.drag);
// Exit any old nodes.
node.exit().remove();
//This will add the name of the author to the node HTML
node.append("author").text(function(d) {return d.author});
//Add the body of the comment to the node
node.append("comment").text(function(d) {return Encoder.htmlDecode(d.body_html)});
//Add the UNIX timestamp to the node
node.append("timestamp").text(function(d) {return moment.unix(d.created_utc).fromNow();})
//On load, assign the root node to the tooltip
numberOfNodes = node[0].length;
rootNode = d3.select(node[0][parseInt(numberOfNodes) - 1]);
rootNodeComment = rootNode.select("comment").text();
rootNodeAuthor = rootNode.select("author").text();
rootNodeTimestamp = rootNode.select("timestamp").text();
// Create the tooltip div for the comments
tooltip_div = d3.select("#"+root_id).append("div")
.attr("class", "tooltip")
.style("opacity", 1);
//Add the HTML to the tooltip for the root
tooltip_div .html("<span class='commentAuthor'>" + rootNodeAuthor + "</span><span class='bulletTimeAgo'>•</span><span class='timestamp'>" + rootNodeTimestamp + "</span><br>" + rootNodeComment)
//Position the tooltip based on the position of the current node, and it's size
.style("left", (rootNode.attr("cx") - (-rootNode.attr("r")) - (-9)) + "px")
.style("top", (rootNode.attr("cy") - 15) + "px");
node.on("mouseover", function() {
currentNode = d3.select(this);
currentTitle = currentNode.select("comment").text();
currentAuthor = currentNode.select("author").text();
currentTimestamp = currentNode.select("timestamp").text();
tooltip_div.transition()
.duration(200)
.style("opacity", 1);
// Add the HTML for all other tooltips on mouseover
tooltip_div .html("<span class='commentAuthor'>" + currentAuthor + "</span><span class='bulletTimeAgo'>•</span><span class='timestamp'>" + currentTimestamp + "</span><br>" + currentTitle)
//Position the tooltip based on the position of the current node, and it's size
.style("left", (currentNode.attr("cx") - (-currentNode.attr("r")) - (-9)) + "px")
.style("top", (currentNode.attr("cy") - 15) + "px");
});
// Fade out the tooltip on mouseout
node.on("mouseout", function(d) {
tooltip_div.transition()
.duration(500)
.style("opacity", 1);
});
// Optimize the JSON output of Reddit for D3
function flatten(root) {
var nodes = [], i = 0, j = 0;
function recurse(node) {
if (node['data']['replies'] != "" && node['kind'] != "more") {
node['data']['replies']['data']['children'].forEach(recurse);
}
if (node['kind'] !="more") {
//Add an ID value to the node starting at 1
node.data.id = ++i;
node.data.name = node.data.body;
//Put the replies in the key 'children' to work with the tree layout
if (node.data.replies != "") {
node.data.children = node.data.replies.data.children;
//Remove the extra 'data' layer for each child
for (j=0; j < node.data.children.length; j++) {
node.data.children[j] = node.data.children[j].data;
}
} else {
node.data.children = "";
}
var comment = node.data;
nodes.push(comment);
}
}
recurse(root);
return nodes;
}
// Optimize the JSON for use with Links
function optimize(linkArray) {
optimizedArray = [];
for (k=0; k < linkArray.length; k++) {
if(typeof linkArray[k].target.count == 'undefined') {
optimizedArray.push(linkArray[k]);
}
}
return optimizedArray;
}
// Get the average net positive upvotes for use in sizing
function getAvgNetPositive() {
var sum = 0;
netPositiveArray = []
//Select all the nodes
var allNodes = d3.selectAll(nodes)[0];
//For each node, get the net positive votes and add it to the sum
for (i=0; i < allNodes.length; i++) {
var netPositiveEach = allNodes[i]["ups"] - allNodes[i]["downs"];
sum += netPositiveEach;
netPositiveArray.push(netPositiveEach);
}
var avgNetPositive = sum/allNodes.length;
return avgNetPositive;
}
function tick(e) {
var kx = .4 * e.alpha, ky = 1.4 * e.alpha;
links.forEach(function(d, i) {
d.target.x += (d.source.x - d.target.x) * kx;
d.target.y += (d.source.y + 80 - d.target.y) * ky;
});
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; });
}
// // Remove the animation effect of the force layout
// while ((force.alpha() > 1e-2) && (k < 150)) {
// force.tick(),
// k = k + 1;
// }
}
Thanks in advance!
You should be able to make several force layouts work at the same time if you encapsulate them in their own namespace, e.g. through separate functions. You can however also do what you want by listening to the end event -- see the documentation. This way, you can "chain" the layouts, starting each one once the previous has finished.
Regarding the other error, it looks like this would be caused by incomplete/faulty data.
First question on Stack Overflow, so bear with me! I am new to d3.js, but have been consistently amazed by what others are able to accomplish with it... and almost as amazed by how little headway I've been able to make with it myself! Clearly I'm not grokking something, so I hope that the kind souls here can show me the light.
My intention is to make a reusable javascript function which simply does the following:
Creates a blank force-directed graph in a specified DOM element
Allows you to add and delete labeled, image-bearing nodes to that graph, specifying connections between them
I've taken http://bl.ocks.org/950642 as a starting point, since that's essentially the kind of layout I want to be able to create:
Here's what my code looks like:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="d3.v2.min.js"></script>
<style type="text/css">
.link { stroke: #ccc; }
.nodetext { pointer-events: none; font: 10px sans-serif; }
body { width:100%; height:100%; margin:none; padding:none; }
#graph { width:500px;height:500px; border:3px solid black;border-radius:12px; margin:auto; }
</style>
</head>
<body>
<div id="graph"></div>
</body>
<script type="text/javascript">
function myGraph(el) {
// Initialise the graph object
var graph = this.graph = {
"nodes":[{"name":"Cause"},{"name":"Effect"}],
"links":[{"source":0,"target":1}]
};
// Add and remove elements on the graph object
this.addNode = function (name) {
graph["nodes"].push({"name":name});
update();
}
this.removeNode = function (name) {
graph["nodes"] = _.filter(graph["nodes"], function(node) {return (node["name"] != name)});
graph["links"] = _.filter(graph["links"], function(link) {return ((link["source"]["name"] != name)&&(link["target"]["name"] != name))});
update();
}
var findNode = function (name) {
for (var i in graph["nodes"]) if (graph["nodes"][i]["name"] === name) return graph["nodes"][i];
}
this.addLink = function (source, target) {
graph["links"].push({"source":findNode(source),"target":findNode(target)});
update();
}
// set up the D3 visualisation in the specified element
var w = $(el).innerWidth(),
h = $(el).innerHeight();
var vis = d3.select(el).append("svg:svg")
.attr("width", w)
.attr("height", h);
var force = d3.layout.force()
.nodes(graph.nodes)
.links(graph.links)
.gravity(.05)
.distance(100)
.charge(-100)
.size([w, h]);
var update = function () {
var link = vis.selectAll("line.link")
.data(graph.links);
link.enter().insert("line")
.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; });
link.exit().remove();
var node = vis.selectAll("g.node")
.data(graph.nodes);
node.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("image")
.attr("class", "circle")
.attr("xlink:href", "https://d3nwyuy0nl342s.cloudfront.net/images/icons/public.png")
.attr("x", "-8px")
.attr("y", "-8px")
.attr("width", "16px")
.attr("height", "16px");
node.append("text")
.attr("class", "nodetext")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
node.exit().remove();
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 + ")"; });
});
// Restart the force layout.
force
.nodes(graph.nodes)
.links(graph.links)
.start();
}
// Make it all go
update();
}
graph = new myGraph("#graph");
// These are the sort of commands I want to be able to give the object.
graph.addNode("A");
graph.addNode("B");
graph.addLink("A", "B");
</script>
</html>
Every time I add a new node, it re-labels all of the existing nodes; these pile on top of each other and things start to get ugly. I understand why this is: because when I call the update() function function upon adding a new node, it does a node.append(...) to the entire data set. I can't figure out how to do this for only the node I'm adding... and I can only apparently use node.enter() to create a single new element, so that doesn't work for the additional elements I need bound to the node. How can I fix this?
Thank you for any guidance that you're able to give on any of this issue!
Edited because I quickly fixed a source of several other bugs that were previously mentioned
After many long hours of being unable to get this working, I finally stumbled across a demo that I don't think is linked any of the documentation: http://bl.ocks.org/1095795:
This demo contained the keys which finally helped me crack the problem.
Adding multiple objects on an enter() can be done by assigning the enter() to a variable, and then appending to that. This makes sense. The second critical part is that the node and link arrays must be based on the force() -- otherwise the graph and model will go out of synch as nodes are deleted and added.
This is because if a new array is constructed instead, it will lack the following attributes:
index - the zero-based index of the node within the nodes array.
x - the x-coordinate of the current node position.
y - the y-coordinate of the current node position.
px - the x-coordinate of the previous node position.
py - the y-coordinate of the previous node position.
fixed - a boolean indicating whether node position is locked.
weight - the node weight; the number of associated links.
These attributes are not strictly needed for the call to force.nodes(), but if these are not present, then they would be randomly initialised by force.start() on the first call.
If anybody is curious, the working code looks like this:
<script type="text/javascript">
function myGraph(el) {
// Add and remove elements on the graph object
this.addNode = function (id) {
nodes.push({"id":id});
update();
}
this.removeNode = function (id) {
var i = 0;
var n = findNode(id);
while (i < links.length) {
if ((links[i]['source'] === n)||(links[i]['target'] == n)) links.splice(i,1);
else i++;
}
var index = findNodeIndex(id);
if(index !== undefined) {
nodes.splice(index, 1);
update();
}
}
this.addLink = function (sourceId, targetId) {
var sourceNode = findNode(sourceId);
var targetNode = findNode(targetId);
if((sourceNode !== undefined) && (targetNode !== undefined)) {
links.push({"source": sourceNode, "target": targetNode});
update();
}
}
var findNode = function (id) {
for (var i=0; i < nodes.length; i++) {
if (nodes[i].id === id)
return nodes[i]
};
}
var findNodeIndex = function (id) {
for (var i=0; i < nodes.length; i++) {
if (nodes[i].id === id)
return i
};
}
// set up the D3 visualisation in the specified element
var w = $(el).innerWidth(),
h = $(el).innerHeight();
var vis = this.vis = d3.select(el).append("svg:svg")
.attr("width", w)
.attr("height", h);
var force = d3.layout.force()
.gravity(.05)
.distance(100)
.charge(-100)
.size([w, h]);
var nodes = force.nodes(),
links = force.links();
var update = function () {
var link = vis.selectAll("line.link")
.data(links, function(d) { return d.source.id + "-" + d.target.id; });
link.enter().insert("line")
.attr("class", "link");
link.exit().remove();
var node = vis.selectAll("g.node")
.data(nodes, function(d) { return d.id;});
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.call(force.drag);
nodeEnter.append("image")
.attr("class", "circle")
.attr("xlink:href", "https://d3nwyuy0nl342s.cloudfront.net/images/icons/public.png")
.attr("x", "-8px")
.attr("y", "-8px")
.attr("width", "16px")
.attr("height", "16px");
nodeEnter.append("text")
.attr("class", "nodetext")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) {return d.id});
node.exit().remove();
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 + ")"; });
});
// Restart the force layout.
force.start();
}
// Make it all go
update();
}
graph = new myGraph("#graph");
// You can do this from the console as much as you like...
graph.addNode("Cause");
graph.addNode("Effect");
graph.addLink("Cause", "Effect");
graph.addNode("A");
graph.addNode("B");
graph.addLink("A", "B");
</script>