I have a force layout graph that works as expected. It reads a graph from a JSON on disk and displays it. I now have the server pushing data to the client page using socket io. This data is a JSON containing the node and link data.
How do I have the force layout refresh and update the layout when it receives this new JSON from the server?
var width = 1900,
height = 1100;
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 networkData = {};
var socket = io.connect('http://localhost:3000');
socket.on("networkData", function (data) {
networkData = data; //This is the data I want to use
});
d3.json("data.json", function(error, graph) { //"data.json" is the data
if (error) throw error; // currently being used
// want to use "networkData"
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", "node")
.attr("r", 5)
.style("fill", "orange")
.call(force.drag);
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; });
});
});
EDIT
I have updated the code as Guillermo Garcia suggested as follows:
socket.on("networkData", function (data) {
force.stop()
render(data);
force
.nodes(data.nodes)
.links(data.links)
.start();
});
function render(data) {
var link = svg.selectAll(".link")
.data(data.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll(".node")
.data(data.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", "orange")
.call(force.drag);
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; });
});
}
However, the graph only works for the first networkData
JSON sent from the server. I also have to manually refresh the page in order for this data to display.
Why is the data not working for the > 2nd data files? How can I have the page dynamically update? (i.e. not have to manually refresh)